﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Frm.Base;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Frm;
using Ledict.Utility.Msg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Frm.DataProcess
{
    /// <summary>
    /// 民事数据处理基础数据部用 连接数据库为67数据库 匹配方式调用词库接口词库匹配
    /// </summary>
    public partial class CivilDataProcessAnalysis : BaseForm
    {
        #region 界面初始化

        //静态锁
        private static readonly object Lock = new object();

        static CivilDataProcessAnalysis _default;
        public static CivilDataProcessAnalysis Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (Lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new CivilDataProcessAnalysis();
                        }
                    }

                }
                return _default;
            }
        }

        ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
        CivilDataProcessAnalysisBLL cdpbll = new CivilDataProcessAnalysisBLL();
        CaseCauseBLL caseCausebll = new CaseCauseBLL();
        static Dictionary<string, SysElementData> ElementWords = new Dictionary<string, SysElementData>();
        SYS_Element_Ruleword_RelBLL serrbll = new SYS_Element_Ruleword_RelBLL();
        DataTable sysElementRuleWords = new DataTable();
        Dictionary<string, string> ccidMatchWords = new Dictionary<string, string>();
        Express_WordBLL ewbll = new Express_WordBLL();
        public static TreeNode clicknode;//点击节点树后，保存该节点
        private List<TreeNode> NodeList = new List<TreeNode>();
        readonly TreeDataBLL trbll = new TreeDataBLL();
        private TreeNode editnode;//点击获得当前节点
        public string FirId = "1000";//默认刑事树ID
        string ewID = string.Empty;
        string ccName = string.Empty;
        string ruleSynforbidword = string.Empty;
        SYS_SiftWordBLL sswb = new SYS_SiftWordBLL();
        SYS_ElementSiftWordBLL seswbll = new SYS_ElementSiftWordBLL();
        DataTable dtSysElementSiftWord = new DataTable();
        /// <summary>
        /// 案由表数据
        /// </summary>
        DataTable dtCaseCause = new DataTable();
        SYS_SiftBdSynBLL ssbsbll = new SYS_SiftBdSynBLL();
        /// <summary>
        /// 筛除同义词表数据
        /// </summary>
        DataTable dtBdSyn = new DataTable();
        thesaurusWrodModel twm = new thesaurusWrodModel();
        /// <summary>
        /// 筛除词表数据
        /// </summary>
        DataTable dtSiftWord = new DataTable();
        DateTime timeGetData = DateTime.Now;
        TimeSpan tsCause;
        Dictionary<string, string> dicGet = new Dictionary<string, string>();
        Dictionary<string, string> dicSql = new Dictionary<string, string>();
        DataTable dtCaseMark = new DataTable();
        DataTable Querydt;//查询结果集
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public CivilDataProcessAnalysis()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            cbtParagraph.SelectedIndex = 0;
            sysElementRuleWords = serrbll.GetSysElementWord();
            dtBdSyn = ssbsbll.GetSiftBdSyn();
            dtSiftWord = sswb.GetSiftWord();
            tabControl2.SelectedTab = tabPageBS;
            dgvBS.AutoGenerateColumns = false;
            dgvBS.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            for (int i = 0; i < dgvBS.ColumnCount; i++)
            {
                if (dgvBS.Columns[i].Name == "EW_Content")
                {
                    dgvBS.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                    dgvBS.Columns[i].Width = 500;
                }
                else
                {
                    dgvBS.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                }
            }
            dgvBS.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;

            dgvGZ.AutoGenerateColumns = false;
            dgvGZ.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvTYC.AutoGenerateColumns = false;
            dgvTYC.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvCP.AutoGenerateColumns = false;
            dgvCP.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //逻辑段默认全部
            cmbLJD.SelectedIndex = 0;
            //是否包含法条内容 默认不包含法条内容
            cmbFT.SelectedIndex = 2;
            dtCaseMark = bll.GetArgumentDtByType("casemark");
            if (dtCaseMark != null && dtCaseMark.Rows.Count > 0)
            {
                DataRow dr = dtCaseMark.NewRow();
                dr["AM_Name"] = "";
                dtCaseMark.Rows.InsertAt(dr, 0);
                cmbDataSignSet.DisplayMember = "AM_Name";
                cmbDataSignSet.ValueMember = "AM_ID";
                cmbDataSignSet.DataSource = dtCaseMark.Copy();
                DataRow dr1 = dtCaseMark.NewRow();
                dr1["AM_Name"] = "全部";
                dtCaseMark.Rows.InsertAt(dr1, 0);
                cmbDataBJ.DisplayMember = "AM_Name";
                cmbDataBJ.ValueMember = "AM_ID";
                cmbDataBJ.DataSource = dtCaseMark;

            }
        }
        #endregion

        #region 显示进度条
        /// <summary>
        /// 显示进度条
        /// </summary>
        /// <param name="maxCount"></param>
        /// <param name="currentCount"></param>
        public void ShowProgress(int maxCount, int currentCount)
        {
            if (progressBar1.InvokeRequired == false)
            {
                if (currentCount < maxCount)
                {
                    progressBar1.Maximum = maxCount;

                    progressBar1.Value = currentCount;
                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("当前{0}条|总共{1}条", currentCount, maxCount);
                }
                else if (currentCount == maxCount)
                {
                    progressBar1.Maximum = maxCount;
                    progressBar1.Value = currentCount;

                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("已完成，共{0}条", maxCount);
                }
            }
            else
            {
                ProcessShow processshow = ShowProgress;
                Invoke(processshow, maxCount, currentCount);
            }
        }
        #endregion

        #region 开始按钮事件
        /// <summary>
        /// 开始按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ElementWords.Clear();
                if (string.IsNullOrEmpty(txtNowProcessNode.Text.Trim()))
                {
                    MsgBox.Warn("请先选择需要处理的案由！");
                    return;
                }
                if (string.IsNullOrEmpty(cbtParagraph.Text.Trim()))
                {
                    MsgBox.Warn("请先选择需要处理的逻辑段！");
                    return;
                }
                if (chkHasOwnNode.Checked)//取案例数据
                {
                    if (string.IsNullOrEmpty(txbALNum.Text.Trim()))
                    {
                        MsgBox.Warn("请先填写取案例数据数量！");
                        txbALNum.Focus();
                        return;
                    }
                    Task.Run(() => { CLData(); });
                }
                else//取数据库中的数据
                {
                    Task.Run(() => { CLDataNew(); });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行数据处理出错！" + ex.Message);
            }
        }
        #endregion

        #region 案例数据数据处理流程
        /// <summary>
        /// 案例数据数据处理流程
        /// </summary>
        public void CLData()
        {
            try
            {
                label1.Text = "正在进行节点数据处理，请稍后...";
                Log.WriteLog("民事数据处理（智能数据部用）处理数据开始时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                DateTime timeBegin = DateTime.Now;

                //根据案由和逻辑段和条数获取需要处理的案例数据
                DataTable dtParagraph = cdpbll.GetDataByType(cbtParagraph.Text.Trim(), txtNowProcessNode.Tag.ToString(), Convert.ToInt32(txbALNum.Text.Trim()));
                TimeSpan ts = DateTime.Now - timeBegin;
                Log.WriteLog("获取到需要处理的案例数据" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + ts.TotalSeconds + "秒");
                timeGetData = DateTime.Now;
                //获取案由下需要处理的节点

                dtCaseCause = caseCausebll.GetCriminalNodes(txtNowProcessNode.Tag.ToString());
                tsCause = DateTime.Now - timeGetData;
                Log.WriteLog("获取到需要处理的节点数据" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");
                timeGetData = DateTime.Now;
                double timeCount = 0;
                Dictionary<int, List<string>> dicTime = new Dictionary<int, List<string>>();
                Dictionary<int, List<string>> dicContent = new Dictionary<int, List<string>>();
                if (dtParagraph != null && dtParagraph.Rows.Count > 0 && dtCaseCause != null && dtCaseCause.Rows.Count > 0)
                {
                    //先删除表中数据
                    ewbll.DeleteProcessNew(txtNowProcessNode.Tag.ToString(), cbtParagraph.Text.Trim() == "本院认为" ? 0 : 1);
                    ElementWords.Clear();
                    //首先先处理所有的节点，获取到规则词，停用词，同义词，禁用词等信息
                    foreach (DataRow dr in dtCaseCause.Rows)
                    {
                        string ccId = dr["CC_ID"].ToString();
                        string ccName = dr["CC_Name"].ToString();
                        if (!ElementWords.ContainsKey(ccId))
                        {
                            if (sysElementRuleWords.Select(" CC_ID='" + ccId + "' ").Length > 0)
                            {
                                DataRow drElement = sysElementRuleWords.Select(" CC_ID='" + ccId + "' ")[0];
                                string ruleWord = drElement["Ruleword"].ToString();
                                string stopWord = drElement["Stopword"].ToString();

                                List<List<string>[]> thesaursTY = new List<List<string>[]>();
                                List<List<string>[]> thesaursJY = new List<List<string>[]>();
                                string RuleWord = drElement["Rule_Synforbidword"].ToString();

                                Dictionary<string, List<List<string>>> dicFC = new Dictionary<string, List<List<string>>>();
                                if (!string.IsNullOrEmpty(RuleWord))
                                {
                                    DataTable dtsbds = ssbsbll.GetSiftBdSyn();
                                    //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                                    string[] res = RuleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (res.Length > 0)
                                    {

                                        foreach (var item in res)
                                        {
                                            List<string> ty = new List<string>();
                                            List<string> jy = new List<string>();
                                            string[] lis = item.Split(':');
                                            if (lis.Length > 0)
                                            {
                                                if (!string.IsNullOrWhiteSpace(lis[0]))
                                                {
                                                    ty.Add(lis[0]);
                                                }
                                                if (!string.IsNullOrWhiteSpace(lis[1]))
                                                {
                                                    string[] st = lis[1].Split(',');
                                                    if (st.Length > 0)
                                                    {
                                                        foreach (var item1 in st)
                                                        {
                                                            if (!string.IsNullOrEmpty(item1))
                                                            {
                                                                if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + lis[0].ToString() + "' and BdSyn='" + item1 + "'").Length > 0)
                                                                {
                                                                }
                                                                else
                                                                {
                                                                    ty.Add(item1);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                if (!string.IsNullOrWhiteSpace(lis[2]))
                                                {
                                                    string[] st = lis[2].Split(',');
                                                    if (st.Length > 0)
                                                    {
                                                        foreach (var item1 in st)
                                                        {
                                                            if (!string.IsNullOrEmpty(item1))
                                                            {
                                                                jy.Add(item1);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (!dicFC.ContainsKey(lis[0]))
                                            {
                                                dicFC.Add(lis[0], new List<List<string>> { ty, jy });
                                            }
                                        }
                                    }
                                }
                                string[] strs = ruleWord.Split(new char[] { '；' }, StringSplitOptions.RemoveEmptyEntries);

                                Dictionary<string, WordTYJY> WordTYJYs = new Dictionary<string, WordTYJY>();
                                if (strs.Length > 0)
                                {
                                    foreach (var item in strs)
                                    {
                                        if (!WordTYJYs.ContainsKey(item))
                                        {
                                            WordTYJYs.Add(item, new WordTYJY() { WordTY = new List<List<string>>(), WordJY = new List<List<string>>() });
                                        }
                                        string[] fcstr = item.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                                        foreach (var item1 in fcstr)
                                        {
                                            if (dicFC.ContainsKey(item1))
                                            {
                                                WordTYJYs[item].WordTY.Add(dicFC[item1][0]);
                                                WordTYJYs[item].WordJY.Add(dicFC[item1][1]);
                                            }
                                        }
                                    }
                                }

                                #region ces 
                                //if (!string.IsNullOrEmpty(RuleWord))
                                //{
                                //    DataTable dtsbds = ssbsbll.GetSiftBdSyn();
                                //    //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                                //    string[] res = RuleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                                //    if (res.Length > 0)
                                //    {

                                //        foreach (var item in res)
                                //        {
                                //            List<string> ty = new List<string>();
                                //            List<string> jy = new List<string>();
                                //            string[] lis = item.Split(':');
                                //            if (lis.Length > 0)
                                //            {
                                //                if (!string.IsNullOrWhiteSpace(lis[0]))
                                //                {
                                //                    ty.Add(lis[0]);
                                //                }
                                //                if (!string.IsNullOrWhiteSpace(lis[1]))
                                //                {
                                //                    string[] st = lis[1].Split(',');
                                //                    if (st.Length > 0)
                                //                    {
                                //                        foreach (var item1 in st)
                                //                        {
                                //                            if (!string.IsNullOrEmpty(item1))
                                //                            {
                                //                                if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + lis[0].ToString() + "' and BdSyn='" + item1 + "'").Length > 0)
                                //                                {
                                //                                }
                                //                                else
                                //                                {
                                //                                    ty.Add(item1);
                                //                                }
                                //                            }
                                //                        }
                                //                    }
                                //                }
                                //                if (!string.IsNullOrWhiteSpace(lis[2]))
                                //                {
                                //                    string[] st = lis[2].Split(',');
                                //                    if (st.Length > 0)
                                //                    {
                                //                        foreach (var item1 in st)
                                //                        {
                                //                            if (!string.IsNullOrEmpty(item1))
                                //                            {
                                //                                jy.Add(item1);
                                //                            }
                                //                        }
                                //                    }
                                //                }
                                //            }
                                //            if (ty.Count > 0)
                                //            {
                                //                thesaursTY.Add(ty);
                                //            }
                                //            if (jy.Count > 0)
                                //            {
                                //                thesaursJY.Add(jy);
                                //            }
                                //        }
                                //    }
                                //} 
                                #endregion
                                ElementWords.Add(ccId, new SysElementData()
                                {
                                    CCID = ccId,
                                    CCName = ccName,
                                    RuleWord = ruleWord,
                                    StopWord = stopWord,
                                    WordTYJY = WordTYJYs
                                });
                            }
                            else
                            {
                                ElementWords.Add(ccId, new SysElementData()
                                {
                                    CCID = ccId,
                                    CCName = ccName,
                                    RuleWord = "",
                                    StopWord = "",
                                    WordTYJY = new Dictionary<string, WordTYJY>()
                                }); ;
                            }
                        }
                    }
                    tsCause = DateTime.Now - timeGetData;
                    Log.WriteLog("处理完需要处理的节点数据" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");

                    label1.Text = "正在进行案例数据处理，请稍后...";

                    ccidMatchWords.Clear();

                    #region 测试数据使用
                    //string str = "原告xxx与被告xxx签订《xxx合同》，自三方签字或者盖章时合同成立并生效，原告xxx已按约定的义务全面履行，被告xxx未归还原告xxx借款本金***元，至xxx止欠的利息***元，已构成违约。";
                    //Match(str.ToString().Trim(), txtNowProcessNode.Tag.ToString());
                    //if (ccidMatchWords.Count > 0)
                    //{
                    //    if (ccidMatchWords.Count > 1)
                    //    {

                    //    }
                    //    foreach (var item in ccidMatchWords.Keys)
                    //    {
                    //        SYS_Express_Word sew = new SYS_Express_Word();
                    //        sew.MS_ID = item;
                    //        sew.EW_Content = str.ToString().Trim();
                    //        sew.EW_CaseId = "";
                    //        sew.ParagraphTypeId = cbtParagraph.SelectedIndex;
                    //        sew.Ruleword = ccidMatchWords[item];
                    //        sew.Word = "";
                    //        ewbll.AddWordProcessNew(sew);
                    //    }
                    //}
                    #endregion
                    Log.WriteLog("开始进行处理案例数据" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 总条数:" + dtParagraph.Rows.Count + "条");
                    //接着分句进行匹配
                    for (int i = 0; i < dtParagraph.Rows.Count; i++)
                    {
                        Log.WriteLog("开始处理案例数据第" + (i + 1) + "条" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                        DateTime timeFirst = DateTime.Now;
                        timeGetData = DateTime.Now;
                        var returnDic = new List<string>();
                        string desc = dtParagraph.Rows[i]["description"].ToString();
                        string caseId = string.Empty;
                        caseId = dtParagraph.Rows[i]["caseId"].ToString();
                        DataTable dtTh = cdpbll.GetDataByCaseId(caseId);
                        if (dtTh != null && dtTh.Rows.Count > 0)
                        {
                            foreach (DataRow item in dtTh.Rows)
                            {
                                if (desc.Contains(item["SP_Name"].ToString().Trim()))
                                {
                                    desc = desc.Replace(item["SP_Name"].ToString().Trim(), "xxx");
                                }
                            }
                        }
                        RegexParse.RegexParse getregex = new RegexParse.RegexParse();
                        var matchschild = getregex.GetParseList("EI2103221352100001", desc);
                        // var matchschild = System.Text.RegularExpressions.Regex.Matches(desc, @"[^。！？\s]*[。！？]"); //分句
                        tsCause = DateTime.Now - timeGetData;
                        Log.WriteLog("第" + (i + 1) + "条数据分句为" + matchschild.Count + "条" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");
                        timeGetData = DateTime.Now;
                        foreach (var strchild in matchschild)
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(strchild.ToString().Trim()))
                                {
                                    ccidMatchWords.Clear();

                                    Log.WriteLog("第" + (i + 1) + "条数据开始进行分词匹配" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                                    Match(strchild.ToString().Trim(), txtNowProcessNode.Tag.ToString());
                                    tsCause = DateTime.Now - timeGetData;
                                    Log.WriteLog("第" + (i + 1) + "条数据进行分词匹配结束" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");
                                    timeGetData = DateTime.Now;
                                    if (ccidMatchWords.Count > 0)
                                    {
                                        Log.WriteLog("第" + (i + 1) + "条数据匹配到节点数量：" + ccidMatchWords.Count + "条,开始插入数据库" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                                        foreach (var item in ccidMatchWords.Keys)
                                        {
                                            bool matchschild1 = getregex.IsMatch("EI2103311600300001", strchild.ToString().Trim());
                                            SYS_Express_Word_ProcessCase sew = new SYS_Express_Word_ProcessCase();
                                            sew.MS_ID = item;
                                            sew.EW_Content = strchild.ToString().Trim();
                                            sew.EW_CaseId = dtParagraph.Rows[i]["caseId"].ToString();
                                            sew.ParagraphTypeId = cbtParagraph.SelectedIndex;
                                            sew.Ruleword = ccidMatchWords[item];
                                            Log.WriteLog("开始获取匹配句分句" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                                            timeGetData = DateTime.Now;
                                            sew.Word = GetWordByContent(strchild.ToString().Trim(), txtNowProcessNode.Tag.ToString(), item);
                                            sew.IsContainsFT = matchschild1 ? 1 : 0;
                                            sew.EW_UseCount = 0;
                                            tsCause = DateTime.Now - timeGetData;
                                            Log.WriteLog("获取匹配句分句功能结束：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");
                                            timeGetData = DateTime.Now;
                                            string ewId = ewbll.Exists_WordProcessCase(sew);
                                            if (!string.IsNullOrEmpty(ewId))
                                            {
                                                bool res = ewbll.UpdateWord_ProcessCase(ewId);
                                            }
                                            else
                                            {
                                                ewbll.AddSYS_ExpressWordProcessCase(sew);
                                            }
                                            tsCause = DateTime.Now - timeGetData;
                                            Log.WriteLog("插入数据到数据库：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");
                                            timeGetData = DateTime.Now;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.WriteLog("匹配节点内容出错：content" + strchild + "ccid" + txtNowProcessNode.Tag.ToString() + ex.Message);
                                continue;
                            }
                        }
                        try
                        {
                            ShowProgress(dtParagraph.Rows.Count, i + 1);
                            caseId = dtParagraph.Rows[i]["caseId"].ToString();
                            Log.WriteLog("开始修改case表状态：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                            cdpbll.UpdateCaseIsComSuit(caseId);
                            tsCause = DateTime.Now - timeGetData;
                            Log.WriteLog("插入数据到数据库：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.TotalSeconds + "秒");
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog("修改case表状态出错：caseId" + caseId + ex.Message);
                            continue;
                        }
                        TimeSpan timeFirstEnd = DateTime.Now - timeFirst;
                        Log.WriteLog("处理案例数据第" + (i + 1) + "条完毕" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + timeFirstEnd.TotalSeconds + "秒");
                        if (!dicTime.ContainsKey(i + 1))
                        {
                            timeCount += timeFirstEnd.TotalSeconds;
                            dicTime.Add(i + 1, new List<string>() { "内容：" + desc, " 耗时：" + timeFirstEnd.TotalSeconds + "秒" });
                        }

                    }
                }
                else
                {
                    MessageBox.Show("没有需要处理的数据信息");
                    label1.Text = "";
                    return;
                }
                timeBegin = DateTime.Now;
                Log.WriteLog("开始处理数据相似度开始:" + timeBegin);
                DataTable dtMsId = ewbll.GetMSIDS(txtNowProcessNode.Tag.ToString());
                DataTable dtEwIdContent = ewbll.GetEwIdAndContent(txtNowProcessNode.Tag.ToString());
                if (dtMsId != null && dtMsId.Rows.Count > 0 && dtEwIdContent.Rows.Count > 0)
                {
                    for (int i = 0; i < dtMsId.Rows.Count; i++)
                    {
                        DataTable dt = dtEwIdContent.Select(" MS_ID='" + dtMsId.Rows[i][0].ToString() + "' ").CopyToDataTable();
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            ChuLi(dt);
                        }
                        ShowProgress(dtMsId.Rows.Count, i + 1);

                    }

                }

                Log.WriteLog("开始处理数据相似度完成:" + DateTime.Now);
                TimeSpan timeEnd = DateTime.Now - timeBegin;
                Log.WriteLog("处理数据相似度结束时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 总耗时：" + timeEnd.TotalSeconds + "秒");

                //TimeSpan timeEnd = DateTime.Now - timeBegin;
                //Log.WriteLog("民事数据处理（智能数据部用）处理数据结束时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 总耗时：" + timeEnd.TotalSeconds + "秒");
                //Log.WriteLog("民事数据处理（智能数据部用）处理数据: 时间：" + timeCount + "条数：" + dicTime.Count + " 平均耗时:" + Convert.ToDouble(timeCount / dicTime.Count) + "秒");
                //foreach (var item in dicTime.Keys)
                //{
                //    Log.WriteLog("第" + item + "条数据" + " 耗时：" + dicTime[item][1] + "秒" + "内容:" + dicTime[item][0]);
                //}
                MessageBox.Show("数据处理完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行数据处理出错！" + ex.Message);
            }
        }
        #endregion

        #region 进行数据相似度数据处理
        /// <summary>
        /// 进行数据相似度数据处理
        /// </summary>
        /// <param name="dt"></param>
        public void ChuLi(DataTable dt)
        {
            double same1 = Ledict.TextDiff.TextComparison.GetTextSameCharsCount("我去北京天安门", "伟大天安门上太原省");
            DataTable dtNew = dt.Clone();
            if (dt != null && dt.Rows.Count > 0)
            {
                string str = dt.Rows[0]["EW_Content"].ToString();
                string ewId1 = dt.Rows[0]["EW_ID"].ToString();
                if (dt.Rows.Count > 1)
                {
                    for (int i = 1; i < dt.Rows.Count; i++)
                    {
                        string str1 = dt.Rows[i]["EW_Content"].ToString();
                        int str1Len = str1.Length;
                        double same = Ledict.TextDiff.TextComparison.GetTextSameCharsCount(str, str1);
                        if (Math.Round(((double)same / str1Len), 2) >= 0.6)
                        {
                            string ewId = dt.Rows[i]["EW_ID"].ToString();
                            ewbll.UpdateProcessFlag(ewId1, ewId);
                        }
                        else
                        {
                            dtNew.ImportRow(dt.Rows[i]);
                        }
                    }
                }
                ewbll.UpdateProcessFlag(ewId1);
            }
            if (dtNew != null && dtNew.Rows.Count > 0)
            {
                ChuLi(dtNew);
            }
        }
        #endregion

        #region 取跑过的数据重新执行
        /// <summary>
        /// 取跑过的数据重新执行
        /// </summary>
        public void CLDataNew()
        {
            ReplayComputer(txtNowProcessNode.Tag.ToString());
            MessageBox.Show("数据处理完成");
        }
        #endregion

        #region  重新执行方法
        /// <summary>
        /// 重新执行方法
        /// </summary>
        /// <param name="ccid"></param>
        /// <param name="ccCXZXID"></param>
        /// <param name="type"></param>
        public void ReplayComputer(string ccid, string ccCXZXID = "", int type = 0)
        {
            try
            {
                //this.Cursor = Cursors.WaitCursor;
                label1.Text = "正在进行节点数据处理，请稍后...";
                DataTable dtParagraph = new DataTable();
                if (type == 0)
                {
                    dtParagraph = ewbll.GetProcessNew(ccid, cbtParagraph.Text.Trim() == "本院认为" ? 0 : 1);
                }
                else
                {
                    dtParagraph = ewbll.GetProcessNew1(ccid);
                }
                if (type == 0)
                {
                    dtCaseCause = caseCausebll.GetCriminalNodes(ccid);
                }
                else
                {
                    dtCaseCause = caseCausebll.GetCriminalNodes(ccCXZXID);
                }
                if (dtParagraph != null && dtParagraph.Rows.Count > 0 && dtCaseCause != null && dtCaseCause.Rows.Count > 0)
                {
                    //先删除表中数据
                    if (type == 0)
                    {
                        ewbll.DeleteProcessNew(ccid, cbtParagraph.Text.Trim() == "本院认为" ? 0 : 1);
                    }
                    else
                    {
                        ewbll.DeleteProcessNew1(ccCXZXID);

                    }
                    foreach (DataRow dr in dtCaseCause.Rows)
                    {
                        string ccId = dr["CC_ID"].ToString();
                        string ccName = dr["CC_Name"].ToString();
                        if (!ElementWords.ContainsKey(ccId))
                        {
                            if (sysElementRuleWords.Select(" CC_ID='" + ccId + "' ").Length > 0)
                            {
                                DataRow drElement = sysElementRuleWords.Select(" CC_ID='" + ccId + "' ")[0];
                                string ruleWord = drElement["Ruleword"].ToString();
                                string stopWord = drElement["Stopword"].ToString();

                                List<List<string>[]> thesaursTY = new List<List<string>[]>();
                                List<List<string>[]> thesaursJY = new List<List<string>[]>();
                                string RuleWord = drElement["Rule_Synforbidword"].ToString();

                                Dictionary<string, List<List<string>>> dicFC = new Dictionary<string, List<List<string>>>();
                                if (!string.IsNullOrEmpty(RuleWord))
                                {
                                    DataTable dtsbds = ssbsbll.GetSiftBdSyn();
                                    //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                                    string[] res = RuleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (res.Length > 0)
                                    {

                                        foreach (var item in res)
                                        {
                                            List<string> ty = new List<string>();
                                            List<string> jy = new List<string>();
                                            string[] lis = item.Split(':');
                                            if (lis.Length > 0)
                                            {
                                                if (!string.IsNullOrWhiteSpace(lis[0]))
                                                {
                                                    ty.Add(lis[0]);
                                                }
                                                if (!string.IsNullOrWhiteSpace(lis[1]))
                                                {
                                                    string[] st = lis[1].Split(',');
                                                    if (st.Length > 0)
                                                    {
                                                        foreach (var item1 in st)
                                                        {
                                                            if (!string.IsNullOrEmpty(item1))
                                                            {
                                                                if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + lis[0].ToString() + "' and BdSyn='" + item1 + "'").Length > 0)
                                                                {
                                                                }
                                                                else
                                                                {
                                                                    ty.Add(item1);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                if (!string.IsNullOrWhiteSpace(lis[2]))
                                                {
                                                    string[] st = lis[2].Split(',');
                                                    if (st.Length > 0)
                                                    {
                                                        foreach (var item1 in st)
                                                        {
                                                            if (!string.IsNullOrEmpty(item1))
                                                            {
                                                                jy.Add(item1);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (!dicFC.ContainsKey(lis[0]))
                                            {
                                                dicFC.Add(lis[0], new List<List<string>> { ty, jy });
                                            }
                                        }
                                    }
                                }
                                string[] strs = ruleWord.Split(new char[] { '；' }, StringSplitOptions.RemoveEmptyEntries);

                                Dictionary<string, WordTYJY> WordTYJYs = new Dictionary<string, WordTYJY>();
                                if (strs.Length > 0)
                                {
                                    foreach (var item in strs)
                                    {
                                        if (!WordTYJYs.ContainsKey(item))
                                        {
                                            WordTYJYs.Add(item, new WordTYJY() { WordTY = new List<List<string>>(), WordJY = new List<List<string>>() });
                                        }
                                        string[] fcstr = item.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                                        foreach (var item1 in fcstr)
                                        {
                                            if (dicFC.ContainsKey(item1))
                                            {
                                                WordTYJYs[item].WordTY.Add(dicFC[item1][0]);
                                                WordTYJYs[item].WordJY.Add(dicFC[item1][1]);
                                            }
                                        }
                                    }
                                }

                                #region ces 
                                //if (!string.IsNullOrEmpty(RuleWord))
                                //{
                                //    DataTable dtsbds = ssbsbll.GetSiftBdSyn();
                                //    //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                                //    string[] res = RuleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                                //    if (res.Length > 0)
                                //    {

                                //        foreach (var item in res)
                                //        {
                                //            List<string> ty = new List<string>();
                                //            List<string> jy = new List<string>();
                                //            string[] lis = item.Split(':');
                                //            if (lis.Length > 0)
                                //            {
                                //                if (!string.IsNullOrWhiteSpace(lis[0]))
                                //                {
                                //                    ty.Add(lis[0]);
                                //                }
                                //                if (!string.IsNullOrWhiteSpace(lis[1]))
                                //                {
                                //                    string[] st = lis[1].Split(',');
                                //                    if (st.Length > 0)
                                //                    {
                                //                        foreach (var item1 in st)
                                //                        {
                                //                            if (!string.IsNullOrEmpty(item1))
                                //                            {
                                //                                if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + lis[0].ToString() + "' and BdSyn='" + item1 + "'").Length > 0)
                                //                                {
                                //                                }
                                //                                else
                                //                                {
                                //                                    ty.Add(item1);
                                //                                }
                                //                            }
                                //                        }
                                //                    }
                                //                }
                                //                if (!string.IsNullOrWhiteSpace(lis[2]))
                                //                {
                                //                    string[] st = lis[2].Split(',');
                                //                    if (st.Length > 0)
                                //                    {
                                //                        foreach (var item1 in st)
                                //                        {
                                //                            if (!string.IsNullOrEmpty(item1))
                                //                            {
                                //                                jy.Add(item1);
                                //                            }
                                //                        }
                                //                    }
                                //                }
                                //            }
                                //            if (ty.Count > 0)
                                //            {
                                //                thesaursTY.Add(ty);
                                //            }
                                //            if (jy.Count > 0)
                                //            {
                                //                thesaursJY.Add(jy);
                                //            }
                                //        }
                                //    }
                                //} 
                                #endregion
                                ElementWords.Add(ccId, new SysElementData()
                                {
                                    CCID = ccId,
                                    CCName = ccName,
                                    RuleWord = ruleWord,
                                    StopWord = stopWord,
                                    WordTYJY = WordTYJYs
                                });
                            }
                            else
                            {
                                ElementWords.Add(ccId, new SysElementData()
                                {
                                    CCID = ccId,
                                    CCName = ccName,
                                    RuleWord = "",
                                    StopWord = "",
                                    WordTYJY = new Dictionary<string, WordTYJY>()
                                }); ;
                            }
                        }
                    }
                    label1.Text = "正在进行案例数据处理，请稍后...";

                    #region 测试数据使用
                    //string str = "证明南方竹业公司提供房产、土地和机器设备作为其***元债务的抵押担保，抵押行为经过公司股东会决议通过，因此签订的抵押合同合法有效。";
                    //Match(str.ToString().Trim(), ccCXZXID);
                    //if (ccidMatchWords.Count > 0)
                    //{
                    //    if (ccidMatchWords.Count > 1)
                    //    {

                    //    }
                    //    foreach (var item in ccidMatchWords.Keys)
                    //    {
                    //        SYS_Express_Word sew = new SYS_Express_Word();
                    //        sew.MS_ID = item;
                    //        sew.EW_Content = str.ToString().Trim();
                    //        sew.EW_CaseId = "";
                    //        sew.ParagraphTypeId = cbtParagraph.SelectedIndex;
                    //        sew.Ruleword = ccidMatchWords[item];
                    //        sew.Word = "";
                    //        ewbll.AddWordProcessNew(sew);
                    //    }
                    //}
                    #endregion
                    //接着分句进行匹配
                    for (int i = 0; i < dtParagraph.Rows.Count; i++)
                    {
                        string content = dtParagraph.Rows[i]["EW_Content"].ToString();
                        int ParagraphTypeId = Convert.ToInt32(dtParagraph.Rows[i]["ParagraphTypeId"].ToString());
                        if (!string.IsNullOrEmpty(content.Trim()))
                        {
                            ccidMatchWords.Clear();
                            if (type == 0)
                            {
                                Match(content.Trim(), ccid);
                            }
                            else
                            {
                                Match(content.Trim(), ccCXZXID);
                            }
                            if (ccidMatchWords.Count > 0)
                            {
                                foreach (var item in ccidMatchWords.Keys)
                                {
                                    SYS_Express_Word_ProcessCase sew = new SYS_Express_Word_ProcessCase();
                                    sew.MS_ID = item;
                                    sew.EW_Content = content.Trim();
                                    sew.EW_CaseId = dtParagraph.Rows[i]["EW_CaseId"].ToString();
                                    sew.ParagraphTypeId = ParagraphTypeId;
                                    sew.Ruleword = ccidMatchWords[item];
                                    //sew.Word = dtParagraph.Rows[i]["Word"].ToString();
                                    sew.IsContainsFT = Convert.ToInt32(dtParagraph.Rows[i]["IsContainsFT"].ToString());
                                    sew.EW_UseCount = Convert.ToInt32(dtParagraph.Rows[i]["EW_UseCount"].ToString());
                                    string ewId = ewbll.Exists_WordProcessCase(sew);
                                    if (!string.IsNullOrEmpty(ewId))
                                    {
                                        bool res = ewbll.UpdateWord_ProcessCase(ewId);
                                    }
                                    else
                                    {
                                        ewbll.AddSYS_ExpressWordProcessCase(sew);
                                    }
                                }
                            }
                        }
                        ShowProgress(dtParagraph.Rows.Count, i + 1);
                    }
                    DateTime timeBegin = DateTime.Now;
                    Log.WriteLog("开始处理数据相似度开始:" + timeBegin);
                    DataTable dtMsId = ewbll.GetMSIDS(ccid);
                    DataTable dtEwIdContent = ewbll.GetEwIdAndContent(ccid);
                    if (dtMsId != null && dtMsId.Rows.Count > 0 && dtEwIdContent.Rows.Count > 0)
                    {
                        for (int i = 0; i < dtMsId.Rows.Count; i++)
                        {
                            DataTable dt = dtEwIdContent.Select(" MS_ID='" + dtMsId.Rows[i][0].ToString() + "' ").CopyToDataTable();
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                ChuLi(dt);
                            }
                            ShowProgress(dtMsId.Rows.Count, i + 1);

                        }

                    }

                    Log.WriteLog("开始处理数据相似度完成:" + DateTime.Now);
                    TimeSpan timeEnd = DateTime.Now - timeBegin;
                    Log.WriteLog("处理数据相似度结束时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 总耗时：" + timeEnd.TotalSeconds + "秒");
                }
                else
                {
                    MessageBox.Show("没有需要处理的数据信息");
                    label1.Text = "";
                    //this.Cursor = Cursors.Default;
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行数据处理出错！" + ex.Message);
            }
            //this.Cursor = Cursors.Default;

        }
        #endregion

        #region 分词匹配流程
        /// <summary>
        /// 分词匹配流程
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ccid"></param>
        public void Match(string content, string ccid)
        {
            try
            {
                if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(ccid))
                {
                    if (ElementWords.ContainsKey(ccid))
                    {
                        SysElementData sed = ElementWords[ccid];
                        if (txtNowProcessNode.Tag != null && ccid == txtNowProcessNode.Tag.ToString())
                        {
                            //符合的数据
                            if (dtCaseCause.Select(" CC_ParentID='" + ccid + "' ").Length > 0)
                            {
                                DataRow[] drs = dtCaseCause.Select(" CC_ParentID='" + ccid + "' ");
                                foreach (var item in drs)
                                {
                                    string ccId1 = item["CC_ID"].ToString();
                                    string ccName1 = item["CC_Name"].ToString();
                                    Match(content, ccId1);
                                }
                            }
                        }
                        else
                        {
                            if (sed.WordTYJY.Count > 0)
                            {
                                foreach (var item2 in sed.WordTYJY.Keys)
                                {
                                    if (sed.WordTYJY[item2].WordTY.Count > 0)
                                    {
                                        List<List<string>> wordTy = sed.WordTYJY[item2].WordTY;
                                        var array = wordTy.Aggregate((m, n) => m.SelectMany(t1 => n.Select(t2 => t1 + "，" + t2).ToList()).ToList()).ToList();
                                        //tsCause = DateTime.Now - timeGetData;
                                        //Log.WriteLog("第" + (i + 1) + "条数据分句为" + matchschild.Count + "条" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + tsCause.Seconds + "秒");
                                        //timeGetData = DateTime.Now;
                                        List<string> lis = IsMatchTYC(content, array);
                                        if (lis.Count > 0)
                                        {
                                            if (sed.WordTYJY[item2].WordJY.Count > 0)
                                            {
                                                //匹配禁用词
                                                if (IsMatchJYC(content, sed.WordTYJY[item2].WordJY))
                                                {

                                                }
                                                else
                                                {

                                                    if (!ccidMatchWords.Keys.Contains(ccid))
                                                    {
                                                        DataRow dr2 = dtCaseCause.Select(" CC_ID='" + ccid + "' ")[0];
                                                        if (dr2["CC_Name"].ToString() != "属性")
                                                        {
                                                            var str = string.Join("，", lis);
                                                            ccidMatchWords.Add(ccid, str);
                                                            if (dtCaseCause.Select(" CC_ID='" + ccid + "' ").Length > 0)
                                                            {
                                                                //如果父级已经匹配则进行删除
                                                                string[] parentid = dtCaseCause.Select(" CC_ID='" + ccid + "' ")[0]["AllParentId"].ToString().Split(',');
                                                                if (parentid.Length > 0)
                                                                {
                                                                    foreach (var item in parentid.ToList())
                                                                    {
                                                                        if (ccidMatchWords.Keys.Contains(item) && item != ccid)
                                                                        {
                                                                            ccidMatchWords.Remove(item);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        //符合的数据
                                                        if (dtCaseCause.Select(" CC_ParentID='" + ccid + "' ").Length > 0)
                                                        {
                                                            DataRow[] drs = dtCaseCause.Select(" CC_ParentID='" + ccid + "' ");
                                                            foreach (var item in drs)
                                                            {
                                                                string ccId1 = item["CC_ID"].ToString();
                                                                Match(content, ccId1);
                                                            }
                                                        }

                                                    }

                                                }
                                            }
                                            else
                                            {

                                                if (!ccidMatchWords.Keys.Contains(ccid))
                                                {
                                                    DataRow dr2 = dtCaseCause.Select(" CC_ID='" + ccid + "' ")[0];
                                                    if (dr2["CC_Name"].ToString() != "属性")
                                                    {
                                                        var str = string.Join("，", lis);
                                                        ccidMatchWords.Add(ccid, str);
                                                        if (dtCaseCause.Select(" CC_ID='" + ccid + "' ").Length > 0)
                                                        {
                                                            //如果父级已经匹配则进行删除
                                                            string[] parentid = dtCaseCause.Select(" CC_ID='" + ccid + "' ")[0]["AllParentId"].ToString().Split(',');
                                                            if (parentid.Length > 0)
                                                            {
                                                                foreach (var item in parentid.ToList())
                                                                {
                                                                    if (ccidMatchWords.Keys.Contains(item) && item != ccid)
                                                                    {
                                                                        ccidMatchWords.Remove(item);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                    //符合的数据
                                                    if (dtCaseCause.Select(" CC_ParentID='" + ccid + "' ").Length > 0)
                                                    {
                                                        DataRow[] drs = dtCaseCause.Select(" CC_ParentID='" + ccid + "' ");
                                                        foreach (var item in drs)
                                                        {
                                                            string ccId1 = item["CC_ID"].ToString();
                                                            string ccName1 = item["CC_Name"].ToString();
                                                            if (ccName1 == "属性")
                                                            {
                                                                if (dtCaseCause.Select(" CC_ParentID='" + ccId1 + "' ").Length > 0)
                                                                {
                                                                    DataRow[] drs1 = dtCaseCause.Select(" CC_ParentID='" + ccId1 + "' ");
                                                                    foreach (var item1 in drs1)
                                                                    {
                                                                        string ccId2 = item1["CC_ID"].ToString();
                                                                        string ccName2 = item1["CC_Name"].ToString();
                                                                        if (ccName2 == "属性")
                                                                        {

                                                                        }
                                                                        else
                                                                        {
                                                                            Match(content, ccId2);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                Match(content, ccId1);
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (sed.RuleWord.Length > 0)
                                        {
                                            string[] strs1 = sed.RuleWord.Split('；');
                                            bool res = false;
                                            if (strs1.Length > 0)
                                            {
                                                foreach (var item in strs1)
                                                {
                                                    string[] strs = item.Split('，');
                                                    foreach (var ite in strs)
                                                    {
                                                        res = content.Contains(ite);
                                                        if (!res)
                                                        {
                                                            break;
                                                        }
                                                    }
                                                    if (res)
                                                    {
                                                        break;
                                                    }
                                                }

                                            }
                                            if (res)
                                            {
                                                if (!ccidMatchWords.Keys.Contains(ccid))
                                                {
                                                    ccidMatchWords.Add(ccid, sed.RuleWord);
                                                    if (dtCaseCause.Select(" CC_ID='" + ccid + "' ").Length > 0)
                                                    {
                                                        //如果父级已经匹配则进行删除
                                                        string[] parentid = dtCaseCause.Select(" CC_ID='" + ccid + "' ")[0]["AllParentId"].ToString().Split(',');
                                                        if (parentid.Length > 0)
                                                        {
                                                            foreach (var item in parentid.ToList())
                                                            {
                                                                if (ccidMatchWords.Keys.Contains(item) && item != ccid)
                                                                {
                                                                    ccidMatchWords.Remove(item);
                                                                }
                                                            }
                                                        }
                                                    }
                                                    //符合的数据
                                                    if (dtCaseCause.Select(" CC_ParentID='" + ccid + "' ").Length > 0)
                                                    {
                                                        DataRow[] drs = dtCaseCause.Select(" CC_ParentID='" + ccid + "' ");
                                                        foreach (var item in drs)
                                                        {
                                                            string ccId1 = item["CC_ID"].ToString();
                                                            string ccName1 = item["CC_Name"].ToString();
                                                            if (ccName1 == "属性")
                                                            {
                                                                if (dtCaseCause.Select(" CC_ParentID='" + ccId1 + "' ").Length > 0)
                                                                {
                                                                    DataRow[] drs1 = dtCaseCause.Select(" CC_ParentID='" + ccId1 + "' ");
                                                                    foreach (var item1 in drs1)
                                                                    {
                                                                        string ccId2 = item1["CC_ID"].ToString();
                                                                        string ccName2 = item1["CC_Name"].ToString();
                                                                        if (ccName2 == "属性")
                                                                        {

                                                                        }
                                                                        else
                                                                        {
                                                                            Match(content, ccId2);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                Match(content, ccId1);
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("匹配节点内容出错：content" + content + "ccid" + ccid + ex.Message);
            }
        }
        #endregion

        #region 是否匹配同义词
        /// <summary>
        /// 是否匹配同义词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="array"></param>
        /// <returns></returns>
        public List<string> IsMatchTYC(string content, List<string> array)
        {

            foreach (var item in array)
            {
                bool res = true;
                string[] strs = item.Split('，');
                foreach (var item1 in strs)
                {
                    res = content.Contains(item1);
                    if (!res)
                    {
                        break;
                    }
                }
                //都为true 是否不包含禁用词
                if (res)
                {
                    return strs.ToList<string>();
                }
            }
            return new List<string>();
        }
        #endregion

        #region 是否匹配禁用词
        /// <summary>
        /// 是否匹配禁用词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="array"></param>
        /// <returns></returns>
        public bool IsMatchJYC(string content, List<List<string>> array)
        {
            bool res = false;
            foreach (var item in array)
            {
                foreach (var item1 in item)
                {
                    res = content.Contains(item1);
                    if (res)
                    {
                        return true;
                    }
                }
            }
            return res;
        }
        #endregion

        #region 获取节点分词（词分词）
        /// <summary>
        /// 获取节点分词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ccid"></param>
        /// <param name="caseCauseCode"></param>
        public void GetWord(string content, string ccid, string caseCauseCode)
        {
            try
            {
                RequestWord rc = new RequestWord() { content = content.Trim(), caseCauseCode = caseCauseCode, industryCode = "通用", isSegment = "是" };
                string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
                WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
                if (model.result.code == "1")
                {
                    List<string> segments = new List<string>();
                    StringBuilder sbRule = new StringBuilder();
                    StringBuilder sbStop = new StringBuilder();
                    List<thesaurusModel> thesaurusModels = model.body;
                    if (thesaurusModels.Count > 0)
                    {
                        //分词的组合
                        List<List<string>> thesaursTY = new List<List<string>>();
                        List<List<string>> thesaursJY = new List<List<string>>();
                        foreach (thesaurusModel item in thesaurusModels)
                        {
                            if (segments.Contains(item.segmentWord))
                            {
                                continue;
                            }
                            else
                            {
                                segments.Add(item.segmentWord);
                            }
                            if (item.isStopWord == "否")
                            {
                                sbRule.Append(item.segmentWord + "，");
                                //同义词
                                if (item.thesaurusWrods.Count > 0)
                                {
                                    //每一个分词的组合
                                    List<string> l1 = new List<string>();
                                    l1.Add(item.segmentWord);
                                    if (item.thesaurusWrods != null)
                                    {
                                        foreach (thesaurusWrodModel item1 in item.thesaurusWrods)
                                        {
                                            if (dtBdSyn != null && dtBdSyn.Rows.Count > 0)
                                            {
                                                if (dtBdSyn.Select(" Ruleword='" + item.segmentWord + "' and BdSyn='" + item1.thesaurusWrod + "' ").Length > 0)
                                                {
                                                    continue;
                                                }
                                            }
                                            if (!l1.Contains(item1.thesaurusWrod))
                                            {
                                                l1.Add(item1.thesaurusWrod);
                                            }
                                        }
                                    }
                                    thesaursTY.Add(l1);
                                }
                                else
                                {
                                    List<string> l1 = new List<string>();
                                    l1.Add(item.segmentWord);
                                    thesaursTY.Add(l1);
                                }
                                //禁用词
                                if (item.forbiddenWords.Count > 0)
                                {
                                    //每一个分词的组合
                                    List<string> l2 = new List<string>();
                                    foreach (wordModel item1 in item.forbiddenWords)
                                    {
                                        if (item1.word != null)
                                        {
                                            foreach (string item2 in item1.word)
                                            {
                                                if (!l2.Contains(item2))
                                                {
                                                    l2.Add(item2);
                                                }
                                            }
                                        }
                                    }
                                    thesaursJY.Add(l2);
                                }

                            }
                            else if (item.isStopWord == "是")
                            {
                                sbStop.Append(item.segmentWord + "，");
                            }
                        }
                        if (!ElementWords.ContainsKey(ccid))
                        {
                            string ruleWord = sbRule.ToString().Length > 0 ? sbRule.ToString().Remove(sbRule.ToString().Length - 1, 1) : "";
                            string stopWord = sbStop.ToString().Length > 0 ? sbStop.ToString().Remove(sbStop.ToString().Length - 1, 1) : "";
                            Dictionary<string, WordTYJY> WordTYJY1 = new Dictionary<string, WordTYJY>();
                            WordTYJY1.Add(content, new WordTYJY() { WordTY = thesaursTY, WordJY = thesaursJY });
                            ElementWords.Add(ccid, new SysElementData()
                            {
                                CCID = ccid,
                                CCName = content,
                                RuleWord = ruleWord,
                                StopWord = stopWord,
                                WordTYJY = WordTYJY1
                            });
                            if (sysElementRuleWords != null && sysElementRuleWords.Rows.Count > 0 && sysElementRuleWords.Select(" CC_ID='" + ccid + "' ").Length > 0)
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord, EW_ID = sysElementRuleWords.Select(" CC_ID='" + ccid + "' ")[0]["EW_ID"].ToString() };
                                serrbll.UpdateName(serr);
                            }
                            else
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord };
                                serrbll.Add(serr);
                            }
                        }
                    }
                    else
                    {
                        if (!ElementWords.ContainsKey(ccid))
                        {
                            string ruleWord = "";
                            string stopWord = "";
                            Dictionary<string, WordTYJY> WordTYJY1 = new Dictionary<string, WordTYJY>();
                            WordTYJY1.Add("", new WordTYJY() { WordTY = new List<List<string>>(), WordJY = new List<List<string>>() });
                            ElementWords.Add(ccid, new SysElementData()
                            {
                                CCID = ccid,
                                CCName = content,
                                RuleWord = ruleWord,
                                StopWord = stopWord,
                                WordTYJY = WordTYJY1
                            });
                            if (sysElementRuleWords != null && sysElementRuleWords.Rows.Count > 0 && sysElementRuleWords.Select(" CC_ID='" + ccid + "' ").Length > 0)
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord, EW_ID = sysElementRuleWords.Select(" CC_ID='" + ccid + "' ")[0]["EW_ID"].ToString() };
                                serrbll.UpdateName(serr);
                            }
                            else
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord };
                                serrbll.Add(serr);
                            }
                        }
                    }
                }
                else if (model.result.code == "0")
                {
                    Log.WriteLog("添加失败！ccid:" + ccid + " content:" + content + model.result.message);
                }
                if (dtCaseCause.Select(" CC_ParentID='" + ccid + "' ").Length > 0)
                {
                    DataRow[] drs = dtCaseCause.Select(" CC_ParentID='" + ccid + "' ");
                    foreach (var item in drs)
                    {
                        string ccId = item["CC_ID"].ToString();
                        string ccName = item["CC_Name"].ToString();
                        if (!string.IsNullOrEmpty(ccId))
                        {
                            GetWord(ccName, ccId, txtNowProcessNode.Tag.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("调用获取词库分词接口发生错误：ccid:" + ccid + " content:" + content + ex.Message);
            }
        }
        #endregion

        #region 获取节点分词通过词库接口（保存语句用）
        /// <summary>
        /// 获取节点分词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ccid"></param>
        /// <param name="caseCauseCode"></param>
        public string GetWordByContent(string content, string caseCauseCode, string msID)
        {
            try
            {
                if (dicGet.ContainsKey(content))
                {
                    ewbll.AddWordAnalysis(dicSql[content].ToString().Replace("CCID", msID));
                    return dicGet[content];
                }
                else
                {
                    RequestWord rc = new RequestWord() { content = content.Trim(), caseCauseCode = caseCauseCode, industryCode = "通用", isSegment = "是" };
                    string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
                    WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
                    if (model.result.code == "1")
                    {
                        List<string> segments = new List<string>();
                        StringBuilder sbRule = new StringBuilder();
                        StringBuilder sbStop = new StringBuilder();
                        StringBuilder strSql = new StringBuilder();
                        List<thesaurusModel> thesaurusModels = model.body;
                        if (thesaurusModels != null && thesaurusModels.Count > 0)
                        {
                            foreach (thesaurusModel item in thesaurusModels)
                            {
                                if (segments.Contains(item.segmentWord))
                                {
                                    continue;
                                }
                                else
                                {
                                    segments.Add(item.segmentWord);
                                }
                                if (item.isStopWord == "否")
                                {
                                    sbRule.Append(item.segmentWord + "，");
                                    strSql.Append(string.Format("  insert into SYS_Express_Word_Analysis values('CCID','{0}');  ", item.segmentWord.Trim()));
                                }
                                else if (item.isStopWord == "是")
                                {
                                    sbStop.Append(item.segmentWord + "，");
                                }
                            }
                            string ruleWord = sbRule.ToString().Length > 0 ? sbRule.ToString().Remove(sbRule.ToString().Length - 1, 1) : "";
                            if (!dicGet.ContainsKey(content))
                            {
                                dicGet.Add(content, ruleWord);
                                dicSql.Add(content, strSql.ToString());
                                ewbll.AddWordAnalysis(strSql.ToString().Replace("CCID", msID));
                            }
                            return ruleWord;
                        }
                        else
                        {
                            return "";
                        }
                    }
                    else if (model.result.code == "0")
                    {
                        Log.WriteLog("添加失败！content:" + content + model.result.message);
                        return "";
                    }
                    else
                    {
                        return "";
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("调用获取词库分词接口发生错误：content:" + content + ex.Message);
                return "";
            }
        }
        #endregion

        #region 放大镜选择节点事件
        /// <summary>
        /// 放大镜选择节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProcessNodeSearch_Click(object sender, EventArgs e)
        {
            var frm = new FrmNodeSelect { TypeName = "民事案由" };
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                var strResult = frm.Tag.ToString();
                frm.Close();
                if (!string.IsNullOrEmpty(strResult))
                {
                    var strArray = strResult.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    txtNowProcessNode.Tag = strArray[0];
                    txtNowProcessNode.Text = strArray[0] + @"(" + strArray[1] + @")";
                }
            }
        }
        #endregion

        #region 树节点选中事件
        /// <summary>
        /// 选中节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (clicknode != null && clicknode.ForeColor != Color.Blue)
            {
                if (e.Node != null)
                {
                    if (clicknode.Text != e.Node.Text)
                    {
                        clicknode.ForeColor = Color.Black;
                    }
                }
            }
            if (e.Node != null)
            {
                clicknode = e.Node;//保存节点
                                   //根据ccid控制添加子节点、同级节点菜单显示             
                                   // if (clicknode.ForeColor != Color.Blue)
                clicknode.ForeColor = Color.Red;
                //    ColorCommonCase_Click(nul);
                tabControl2_SelectedIndexChanged(null, null);//右侧信息展现
            }
        }
        #endregion

        #region 表述管理、规则管理菜单页切换
        /// <summary>
        /// 表述管理、规则管理菜单页切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            switch (tabControl2.SelectedTab.Name)
            {
                //表述管理
                case "tabPageBS":
                    if (clicknode != null)
                    {
                        rtbNew1.Text = txbRemark.Text = "";
                        GetGPC();
                        dataPagerMain.ChangePageNumber(1);
                        dgvBS.ClearSelection();
                    }
                    break;
                //规则管理
                case "tabPageGZ":
                    if (clicknode != null)
                    {
                        DataTable dt2 = serrbll.GetSysElementWord(clicknode.Tag.ToString());
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            dgvGZ.DataSource = dt2;
                        }
                        else
                        {
                            DataTable dtt = (DataTable)dgvGZ.DataSource;
                            if (dtt != null)
                            { dtt.Rows.Clear(); }
                            dgvGZ.DataSource = dtt;
                        }
                        dgvGZ.ClearSelection();
                    }
                    break;
            }
            this.Cursor = Cursors.Default;
        }
        #endregion

        #region SysElementData类
        /// <summary>
        /// SysElementData类
        /// </summary>
        public class SysElementData
        {
            /// <summary>
            /// ccid
            /// </summary>
            public string CCID { get; set; }

            /// <summary>
            /// 节点名称
            /// </summary>
            public string CCName { get; set; }

            /// <summary>
            /// 规则词 多个用中文逗号隔开
            /// </summary>
            public string RuleWord { get; set; }

            /// <summary>
            /// 停用词 多个用中文逗号隔开
            /// </summary>
            public string StopWord { get; set; }


            /// <summary>
            /// 同义词禁用词的组合
            /// </summary>
            public Dictionary<string, WordTYJY> WordTYJY { get; set; }

            /// <summary>
            /// 同义词的组合
            /// </summary>
            //public List<List<string>[]> WordTY { get; set; }

            ///// <summary>
            ///// 禁用词的组合
            ///// </summary>
            //public List<List<string>[]> WordJY { get; set; }
        }

        /// <summary>
        /// 同义词禁用词的组合
        /// </summary>
        public class WordTYJY
        {
            /// <summary>
            /// 同义词的组合
            /// </summary>
            public List<List<string>> WordTY { get; set; }

            ///// <summary>
            ///// 禁用词的组合
            ///// </summary>
            public List<List<string>> WordJY { get; set; }
        }

        #endregion



        #region 给DataTable添加序号列，名称为Num
        /// <summary>
        /// 给DataTable添加序号列，名称为Num
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public DataTable AddDataTableNumA(DataTable dt)
        {
            DataTable dtNew = dt.Clone();
            if (dt != null && dt.Rows.Count > 0)
            {
                dtNew.Columns.Add("Num");
                int j = 1;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dtSiftWord.Select("Siftword='" + dt.Rows[i]["content"].ToString() + "' ").Length > 0)
                    {
                        continue;
                    }
                    else
                    {
                        dtNew.ImportRow(dt.Rows[i]);
                        dtNew.Rows[dtNew.Rows.Count - 1]["Num"] = j;
                        j++;
                    }

                }
                return dtNew;
            }
            else
            {
                return dtNew;
            }
        }
        #endregion

        #region 获取高频词数据
        /// <summary>
        /// 获取高频词数据
        /// </summary>
        public void GetGPC()
        {
            int Num = clicknode.Text.IndexOf('(') != -1 ? Convert.ToInt32(clicknode.Text.Trim().Substring(clicknode.Text.IndexOf('(') + 1).Replace(')', ' ').Trim()) : 0;
            DataTable gpcDt = ewbll.GetGPCData(clicknode.Tag.ToString(), Num);
            if (gpcDt != null && gpcDt.Rows.Count > 0)
            {
                gpcDt = AddDataTableNumA(gpcDt);
                if (gpcDt != null && gpcDt.Rows.Count > 0)
                {
                    dgvCP.DataSource = gpcDt;
                }
                else
                {
                    DataTable dtt = (DataTable)dgvCP.DataSource;
                    if (dtt != null)
                    { dtt.Rows.Clear(); }
                    dgvCP.DataSource = dtt;
                }
            }
            else
            {
                DataTable dtt = (DataTable)dgvCP.DataSource;
                if (dtt != null)
                { dtt.Rows.Clear(); }
                dgvCP.DataSource = dtt;
            }
            #region
            //DataTable dt1 = ewbll.GetExtraceContentNew(clicknode.Tag.ToString());
            //if (dt1 != null && dt1.Rows.Count > 0)
            //{
            //    dt1 = PublicMethod.AddDataTableNum(dt1);
            //    //高频词统计公式：当前分词所在的表述句数量/当前节点的所有表述句数量
            //    Dictionary<string, string> dics = new Dictionary<string, string>();
            //    int zum = dt1.Rows.Count;
            //    foreach (DataRow dr in dt1.Rows)
            //    {
            //        if (!string.IsNullOrEmpty(dr["Word"].ToString()))
            //        {
            //            string[] strs = dr["Word"].ToString().Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
            //            if (strs.Length > 0)
            //            {
            //                foreach (var item in strs.ToList())
            //                {
            //                    if (dtSiftWord.Select("Siftword='" + item + "' ").Length > 0)
            //                    {
            //                        continue;
            //                    }
            //                    if (!dics.ContainsKey(item))
            //                    {
            //                        dics.Add(item, "1");
            //                    }
            //                    else
            //                    {
            //                        dics[item] = Convert.ToString(Convert.ToInt32(dics[item]) + 1);
            //                    }
            //                }
            //            }
            //        }
            //    }
            //    if (dics.Count > 0)
            //    {
            //        foreach (var item in dics.Keys.ToArray())
            //        {
            //            if ((double)Convert.ToInt32(dics[item]) / zum > 0.5)
            //            {
            //                dics[item] = ((double)Convert.ToInt32(dics[item]) / zum).ToString("P");
            //            }
            //            else
            //            {
            //                dics.Remove(item);
            //            }
            //        }
            //    }
            //    if (dics.Count > 0)
            //    {
            //        DataTable dt = new DataTable();
            //        dt.Columns.Add("content");
            //        dt.Columns.Add("CP");
            //        foreach (var item in dics.Keys)
            //        {
            //            DataRow dr = dt.NewRow();
            //            dr["content"] = item;
            //            dr["CP"] = dics[item];
            //            dt.Rows.Add(dr);
            //        }
            //        if (dt != null && dt.Rows.Count > 0)
            //        {
            //            dt = PublicMethod.AddDataTableNum(dt);
            //            dgvCP.DataSource = dt;
            //        }
            //    }
            //    else
            //    {
            //        DataTable dtt = (DataTable)dgvCP.DataSource;
            //        if (dtt != null)
            //        { dtt.Rows.Clear(); }
            //        dgvCP.DataSource = dtt;

            //    }
            //    dgvBS.DataSource = dt1;
            //}
            //else
            //{
            //    DataTable dtt = (DataTable)dgvBS.DataSource;
            //    if (dtt != null)
            //    { dtt.Rows.Clear(); }
            //    dgvBS.DataSource = dtt;
            //    DataTable dtt1 = (DataTable)dgvCP.DataSource;
            //    if (dtt1 != null)
            //    { dtt1.Rows.Clear(); }
            //    dgvCP.DataSource = dtt1;
            //}
            #endregion
        }
        #endregion

        #region 表述管理列单击事件（对勾 × 全选）
        /// <summary>
        /// 表述管理列单击事件（对勾 × 全选）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvBS_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //4对勾5×
                if (e.ColumnIndex == 6 || e.ColumnIndex == 7)
                {
                    var checkCellRight = (DataGridViewCheckBoxCell)dgvBS.Rows[e.RowIndex].Cells["EW_Right"];
                    var checkCellwrong = (DataGridViewCheckBoxCell)dgvBS.Rows[e.RowIndex].Cells["EW_Wrong"];
                    if (e.ColumnIndex == 6)
                    {
                        if (checkCellRight.Value != DBNull.Value && Convert.ToBoolean(checkCellRight.Value))
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                        else
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }

                    }
                    if (e.ColumnIndex == 7)
                    {
                        if (checkCellwrong.Value != DBNull.Value && Convert.ToBoolean(checkCellwrong.Value))
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }
                        else
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                    }

                    ewID = dgvBS.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        ewbll.UpdateWordProcessNew(ewID, 0);
                    }
                    if (Convert.ToBoolean(checkCellwrong.Value))
                    {
                        ewbll.UpdateWordProcessNew(ewID, 1);
                    }
                    // tabControl2_SelectedIndexChanged(null, null);//右侧信息展现
                }
                else if (e.ColumnIndex == 2)  //编辑文本
                {

                    ewID = dgvBS.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[e.RowIndex].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[e.RowIndex].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }
                }
                else if (e.ColumnIndex == 13)  //相似句数量
                {

                    ewID = dgvBS.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                    int num = Convert.ToInt32(dgvBS.Rows[e.RowIndex].Cells["XSNum"].Value.ToString());
                    if (num > 0)
                    {
                        DataTable dt = ewbll.GetXSData(ewID);
                        XSData xs = new XSData(dt);
                        xs.ShowDialog();
                    }
                }
            }
            else if (e.RowIndex == -1)
            {
                string revalue = this.dgvBS.Rows[0].Cells[0].EditedFormattedValue.ToString().ToLower();
                if (revalue == "false")
                {
                    for (int i = 0; i < dgvBS.Rows.Count; i++)
                    {
                        this.dgvBS.Rows[i].Cells[0].Value = "true";
                    }
                }
                else
                {
                    for (int i = 0; i < dgvBS.Rows.Count; i++)
                    {
                        this.dgvBS.Rows[i].Cells[0].Value = "false";
                    }
                }
                this.dgvBS.EndEdit();
            }
        }
        #endregion

        #region 中间文本框定位
        /// <summary>
        /// 中间文本框定位
        /// </summary>
        /// <param name="contextExtractValue"></param>
        private void PositionExtractValueNew(string contextExtractValue)
        {
            int start = 0;
            int end = this.rtbNew1.Text.Length;
            int index = rtbNew1.Find(contextExtractValue, start, end, RichTextBoxFinds.None);
            int js = 0;
            if (index == -1)//不连贯的文本循环定位
            {
                string[] cfTQContext = contextExtractValue.Split('\r');
                int zjs = 0;
                for (int i = 0; i < cfTQContext.Length; i++)
                {
                    string newcontext = cfTQContext[i].ToString();
                    if (!string.IsNullOrEmpty(newcontext))
                    {
                        int startnew = 0;
                        index = rtbNew1.Find(newcontext, startnew, end, RichTextBoxFinds.None);
                        while (index != -1)
                        {
                            zjs++;
                            rtbNew1.SelectionFont = new System.Drawing.Font(rtbNew1.SelectionFont, FontStyle.Underline | FontStyle.Bold);
                            rtbNew1.SelectionColor = Color.Red;
                            if (zjs == 1)
                            {
                                rtbNew1.ScrollToCaret();
                            }
                            if (zjs > 100)
                            {
                                break;
                            }
                            start = index + newcontext.Length;
                            if (start == end)
                            {
                                index = -1;
                            }
                            else
                            {
                                index = rtbNew1.Find(newcontext, start, end, RichTextBoxFinds.None);
                            }
                        }
                    }
                }
            }
            while (index != -1)
            {
                //  rtbNew1.SelectedText
                rtbNew1.SelectionFont = new System.Drawing.Font(rtbNew1.SelectionFont, FontStyle.Underline | FontStyle.Bold);
                rtbNew1.SelectionColor = Color.Red;
                rtbNew1.ScrollToCaret();
                start = index + contextExtractValue.Length;
                index = rtbNew1.Find(contextExtractValue, start, end, RichTextBoxFinds.None);
                js++;
                if (js > 100)
                    break;
            }
        }
        #endregion

        #region 保存备注
        /// <summary>
        /// 保存备注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            //if (!string.IsNullOrEmpty(txbRemark.Text.Trim()))
            //{
            if (!string.IsNullOrEmpty(ewID))
            {
                bool res = ewbll.UpdateWordProcessNew(ewID, 2, txbRemark.Text.Trim());
                if (res)
                {
                    int row = this.dgvBS.CurrentRow.Index;
                    dgvBS.Rows[row].Cells["Remark"].Value = txbRemark.Text.Trim();
                    MessageBox.Show("保存成功！");
                    return;
                }
                else
                {
                    MessageBox.Show("保存失败！");
                    return;
                }
            }
            else
            {
                MessageBox.Show("请先选择需要添加备注的表述句");
                return;
            }
            //}
            //else
            //{
            //    MessageBox.Show("请先填写备注信息！");
            //    txbRemark.Focus();
            //    return;
            //}
        }
        #endregion

        #region 节点树查询事件
        /// <summary>
        /// 节点树查询事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeBtn_Click(object sender, EventArgs e)
        {
            QueryNode();
        }
        #endregion

        #region 节点树查询
        /// <summary>
        /// 开始查询
        /// </summary>
        private void QueryNode()
        {
            var QueryNodeName = QueryNodeTxt.Text.Trim();//查询关键字
            if (QueryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, QueryNodeName, 1);//查询结果
                MaxCount.Text = Querydt.Rows.Count.ToString();//总数
                if (Querydt.Rows.Count > 0)
                {
                    CurrentCount.Text = "1";//当前节点条数
                    SkipNumber.Text = CurrentCount.Text;//跳转文本框
                    var CurrNode = Convert.ToInt32(CurrentCount.Text);//当前节点条数
                    LinkIsVisible(CurrNode);//上一条下一条是否可用
                    QueryNode_Page(Querydt, CurrNode);//定位到目标节点
                }
                else
                {
                    CurrentCount.Text = "0";//没结果
                    SkipNumber.Text = CurrentCount.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }
        #endregion

        #region 上一条下一条是否可用
        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)//当前小于1
            {
                Prelinkbtn.Enabled = false;//上一页不可用
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;//下一页不可用
            }
        }
        #endregion

        #region 定位到目标节点
        /// <summary>
        /// 定位到目标节点
        /// </summary>
        /// <param name="dt">查询返回结果集</param>
        /// <param name="showindex">第几条</param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex && showindex > 0)
            {
                var NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');//所有父级
                for (var i = 0; i < NotePidArr.Length; i++)
                {
                    if (i != NotePidArr.Length - 1)
                    {
                        var Node = FindNode(NotePidArr[i]);
                        if (Node != null)
                        {
                            Node.Expand();//拖出所有父级节点
                        }
                        //TreeNode tnRet = null;
                        //foreach (TreeNode item in tVCaseCause.Nodes)
                        //{
                        //    tnRet = FindNodeByValue(item, NotePidArr[i].ToString());
                        //    if (tnRet != null) break;
                        //}
                        //if (tnRet != null)
                        //{
                        //    tnRet.Expand();
                        //}
                    }
                    else  //最后一级节点为查找节点
                    {
                        // tVCaseCause.ExpandAll();
                        var node = FindNode(NotePidArr[i]);

                        //TreeNode tnRet = null;
                        //foreach (TreeNode item in tVCaseCause.Nodes)
                        //{
                        //    tnRet = FindNodeByValue(item, NotePidArr[i].ToString());
                        //    if (tnRet != null) break;
                        //}
                        //// TreeNode[] obj = tVCaseCause.Nodes.Find(node.Text, true);
                        // tVCaseCause.SelectedNode = null;
                        tVCaseCause.SelectedNode = node;//定位          
                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }
        }
        #endregion

        #region 查找节点
        /// <summary>
        /// 查找节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (var node in NodeList)//遍历现在界面上的所有节点
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;
            //return (TreeNode)NodeList[Nodeid];
        }
        #endregion

        #region 加载民事节点树
        /// <summary>
        /// 加载民事节点树
        /// </summary>
        public void CaseCauseTree()
        {
            string TypeName = "民事案由";
            #region 初始化
            tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            MaxCount.Text = "";
            CurrentCount.Text = "";
            SkipNumber.Text = "";
            #endregion

            var dt = trbll.GetCauseTree_Two("", 0);// 第一层

            if (dt.Rows.Count > 0)
            {
                var arrayDR = dt.Select("name='" + TypeName + "'");

                foreach (var caseTreeNodeRode in arrayDR)
                {
                    var node = new TreeNode();

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
                    node.Tag = caseTreeNodeRode["id"];
                    node.Name = LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"] + "," + caseTreeNodeRode["TableName"]);
                    FirId = caseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 0).Rows.Count > 0)//第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }

        }
        #endregion

        #region 窗体加载事件
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CivilDataProcessAnalysis_Load(object sender, EventArgs e)
        {
            CaseCauseTree();
        }
        #endregion

        #region 节点树鼠标按下事件
        /// <summary>
        /// 节点树鼠标按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            var ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
            }
        }
        #endregion

        #region 节点树展开事件
        /// <summary>
        /// 节点树展开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            try
            {
                e.Node.Nodes.Clear();
                CaseCauseTreeChild(e.Node);
            }
            catch (Exception ex)
            {
                Log.WriteLog("展开列表发生错误：" + ex.Message);
                MessageBox.Show("展开列表发生错误：" + ex.Message);
            }
        }
        #endregion

        #region 获取下级树
        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();// 父级ID
            var caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode();
                int num = ewbll.GetProcessCount(caseTreeNodeRode.Rows[i]["id"].ToString());
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]) + (num > 0 ? "(" + num.ToString() + ")" : "");
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有无下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);//父级节点添加节点
                TreeNode node1 = null;
                foreach (var node2 in NodeList)//遍历现在界面上的所有节点
                {
                    if (node2.Tag.ToString() == node.Tag.ToString())
                    {
                        node1 = node2;
                        break;
                    }
                }
                if (node1 != null)
                {
                    NodeList.Remove(node1);
                    NodeList.Add(node);//list用来查询
                }
                else
                {
                    NodeList.Add(node);
                }
            }
        }
        #endregion

        #region 节点树Go事件
        /// <summary>
        /// 节点树Go事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            var CurrNode = Convert.ToInt32(SkipNumber.Text);//当前节点条数
            if (Querydt != null && !string.IsNullOrEmpty(QueryNodeTxt.Text.Trim()))
            {
                if (Querydt.Rows.Count >= CurrNode)
                {
                    CurrentCount.Text = SkipNumber.Text;//跳转
                    QueryNode_Page(Querydt, CurrNode);//定位到目标节点
                    LinkIsVisible(CurrNode);// 上一条下一条是否可用
                }
                else
                {
                    MessageBox.Show("跳转页码有误，重新输入！");
                }
            }
        }
        #endregion

        #region 节点树下一条
        /// <summary>
        /// 节点树下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrentCount.Text))
            {
                CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) + 1).ToString();//下一条
                SkipNumber.Text = CurrentCount.Text;
                var CurrNode = Convert.ToInt32(CurrentCount.Text);
                QueryNode_Page(Querydt, CurrNode);//定位查询
                LinkIsVisible(CurrNode);
            }
        }
        #endregion

        #region 节点树上一条
        /// <summary>
        /// 节点树上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!String.IsNullOrEmpty(CurrentCount.Text))
            {
                CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) - 1).ToString();//上一条
                SkipNumber.Text = CurrentCount.Text;
                var CurrNode = Convert.ToInt32(CurrentCount.Text);
                QueryNode_Page(Querydt, CurrNode);//定位查询
                LinkIsVisible(CurrNode);
            }
        }
        #endregion

        #region 导出功能
        /// <summary>
        /// 导出功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDC_Click(object sender, EventArgs e)
        {
            if (clicknode != null)
            {
                DaoChuWindow dl = new DaoChuWindow(clicknode.Tag.ToString());
                dl.ShowDialog();
            }
        }
        #endregion

        #region 弃用
        private void dgvGZ_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e != null && e.RowIndex > -1)
            {
                string ccid = dgvGZ.Rows[e.RowIndex].Cells["CC_ID"].Value.ToString();
                ccName = dgvGZ.Rows[e.RowIndex].Cells["CC_Name"].Value.ToString();
                if (dgvGZ.Rows[e.RowIndex].Cells["Rule_Synforbidword"].Value != null)
                {
                    string RuleWord = dgvGZ.Rows[e.RowIndex].Cells["Rule_Synforbidword"].Value.ToString();
                    if (!string.IsNullOrEmpty(RuleWord))
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add(new DataColumn("RuleName"));
                        dt.Columns.Add(new DataColumn("TYName"));
                        dt.Columns.Add(new DataColumn("Check"));
                        DataTable dtJY = new DataTable();
                        dtJY.Columns.Add(new DataColumn("RuleName"));
                        dtJY.Columns.Add(new DataColumn("JYName"));
                        //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                        string[] res = RuleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {

                            foreach (var item in res)
                            {
                                List<string> ty = new List<string>();
                                List<string> jy = new List<string>();
                                string[] lis = item.Split(':');
                                if (lis.Length > 0)
                                {
                                    string gzc = string.Empty;
                                    if (!string.IsNullOrWhiteSpace(lis[0]))
                                    {
                                        gzc = lis[0];
                                    }
                                    if (!string.IsNullOrWhiteSpace(gzc) && !string.IsNullOrWhiteSpace(lis[1]))
                                    {
                                        string[] st = lis[1].Split(',');
                                        if (st.Length > 0)
                                        {
                                            foreach (var item1 in st)
                                            {
                                                if (!string.IsNullOrEmpty(item1))
                                                {
                                                    DataRow dr = dt.NewRow();
                                                    dr["RuleName"] = gzc;
                                                    dr["TYName"] = item1;
                                                    dt.Rows.Add(dr);
                                                }
                                            }
                                        }
                                    }
                                    if (!string.IsNullOrWhiteSpace(gzc) && !string.IsNullOrWhiteSpace(lis[2]))
                                    {
                                        string[] st = lis[2].Split(',');
                                        if (st.Length > 0)
                                        {
                                            foreach (var item1 in st)
                                            {
                                                if (!string.IsNullOrEmpty(item1))
                                                {
                                                    DataRow dr = dtJY.NewRow();
                                                    dr["RuleName"] = gzc;
                                                    dr["JYName"] = item1;
                                                    dtJY.Rows.Add(dr);
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                        }
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            dgvTYC.DataSource = dt;
                        }
                        else
                        {
                            DataTable dtt = (DataTable)dgvTYC.DataSource;
                            if (dtt != null)
                            { dtt.Rows.Clear(); }
                            dgvTYC.DataSource = dtt;
                        }

                        if (dtJY != null && dtJY.Rows.Count > 0)
                        {
                            dgvJYC.DataSource = dt;
                        }
                        else
                        {
                            DataTable dtt = (DataTable)dgvJYC.DataSource;
                            if (dtt != null)
                            { dtt.Rows.Clear(); }
                            dgvJYC.DataSource = dtt;
                        }
                    }
                    else
                    {
                        DataTable dtt = (DataTable)dgvTYC.DataSource;
                        if (dtt != null)
                        { dtt.Rows.Clear(); }
                        dgvTYC.DataSource = dtt;
                        DataTable dtt1 = (DataTable)dgvJYC.DataSource;
                        if (dtt1 != null)
                        { dtt1.Rows.Clear(); }
                        dgvJYC.DataSource = dtt1;
                    }
                    //GetTYC(ccName);
                }
            }
        }
        /// <summary>
        /// 获取节点分词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ccid"></param>
        /// <param name="caseCauseCode"></param>
        public DataTable GetWordTY(string content, string caseCauseCode)
        {
            try
            {
                DataTable dtsbds = ssbsbll.GetSiftBdSyn();
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("RuleName"));
                dt.Columns.Add(new DataColumn("TYName"));
                dt.Columns.Add(new DataColumn("Check"));
                RequestWord rc = new RequestWord() { content = content.Trim(), caseCauseCode = caseCauseCode, industryCode = "通用" };
                string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
                WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
                if (model.result.code == "1")
                {
                    List<string> segments = new List<string>();
                    List<thesaurusModel> thesaurusModels = model.body;
                    if (thesaurusModels.Count > 0)
                    {
                        //分词的组合
                        foreach (thesaurusModel item in thesaurusModels)
                        {
                            if (segments.Contains(item.segmentWord))
                            {
                                continue;
                            }
                            else
                            {
                                segments.Add(item.segmentWord);
                            }
                            if (item.isStopWord == "否")
                            {
                                //同义词
                                if (item.thesaurusWrods.Count > 0)
                                {
                                    //每一个分词的组合
                                    List<string> l1 = new List<string>();
                                    l1.Add(item.segmentWord);
                                    if (item.thesaurusWrods != null)
                                    {
                                        foreach (thesaurusWrodModel item1 in item.thesaurusWrods)
                                        {
                                            DataRow dr = dt.NewRow();
                                            dr["RuleName"] = item.segmentWord;
                                            dr["TYName"] = item1.thesaurusWrod;
                                            if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + item.segmentWord + "' and BdSyn='" + item1.thesaurusWrod + "'").Length > 0)
                                            {
                                            }
                                            else
                                            {
                                                dt.Rows.Add(dr);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return dt;
                }
                else if (model.result.code == "0")
                {
                    Log.WriteLog("添加失败！content:" + content + model.result.message);
                    return new DataTable();
                }
                else
                {
                    return new DataTable();
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("调用获取词库分词接口发生错误：content:" + content + ex.Message);
                return new DataTable();
            }
        }
        #endregion

        #region 获取同义词
        /// <summary>
        /// 获取同义词
        /// </summary>
        /// <param name="ruleWord"></param>
        public void GetTYC(string ruleWord)
        {
            if (!string.IsNullOrEmpty(ruleWord))
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("RuleName"));
                dt.Columns.Add(new DataColumn("TYName"));
                dt.Columns.Add(new DataColumn("Check"));
                DataTable dtJY = new DataTable();
                dtJY.Columns.Add(new DataColumn("RuleName"));
                dtJY.Columns.Add(new DataColumn("JYName"));
                //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                string[] res = ruleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                if (res.Length > 0)
                {
                    DataTable dtsbds = ssbsbll.GetSiftBdSyn();

                    foreach (var item in res)
                    {
                        List<string> ty = new List<string>();
                        List<string> jy = new List<string>();
                        string[] lis = item.Split(':');
                        if (lis.Length > 0)
                        {
                            string gzc = string.Empty;
                            if (!string.IsNullOrWhiteSpace(lis[0]))
                            {
                                gzc = lis[0];
                            }
                            if (!string.IsNullOrWhiteSpace(gzc) && !string.IsNullOrWhiteSpace(lis[1]))
                            {
                                string[] st = lis[1].Split(',');
                                if (st.Length > 0)
                                {
                                    foreach (var item1 in st)
                                    {
                                        if (!string.IsNullOrEmpty(item1))
                                        {
                                            DataRow dr = dt.NewRow();
                                            dr["RuleName"] = gzc;
                                            dr["TYName"] = item1;
                                            if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + gzc + "' and BdSyn='" + item1 + "'").Length > 0)
                                            {
                                            }
                                            else
                                            {
                                                dt.Rows.Add(dr);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrWhiteSpace(gzc) && !string.IsNullOrWhiteSpace(lis[2]))
                            {
                                string[] st = lis[2].Split(',');
                                if (st.Length > 0)
                                {
                                    foreach (var item1 in st)
                                    {
                                        if (!string.IsNullOrEmpty(item1))
                                        {
                                            DataRow dr = dtJY.NewRow();
                                            dr["RuleName"] = gzc;
                                            dr["JYName"] = item1;
                                            dtJY.Rows.Add(dr);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
                if (dt != null && dt.Rows.Count > 0)
                {
                    dgvTYC.DataSource = dt;
                }
                else
                {
                    DataTable dtt = (DataTable)dgvTYC.DataSource;
                    if (dtt != null)
                    { dtt.Rows.Clear(); }
                    dgvTYC.DataSource = dtt;
                }

                if (dtJY != null && dtJY.Rows.Count > 0)
                {
                    dgvJYC.DataSource = dt;
                }
                else
                {
                    DataTable dtt = (DataTable)dgvJYC.DataSource;
                    if (dtt != null)
                    { dtt.Rows.Clear(); }
                    dgvJYC.DataSource = dtt;
                }
            }
            else
            {
                DataTable dtt = (DataTable)dgvTYC.DataSource;
                if (dtt != null)
                { dtt.Rows.Clear(); }
                dgvTYC.DataSource = dtt;
                DataTable dtt1 = (DataTable)dgvJYC.DataSource;
                if (dtt1 != null)
                { dtt1.Rows.Clear(); }
                dgvJYC.DataSource = dtt1;
            }
        }
        #endregion

        #region 同义词列表项选中事件
        /// <summary>
        /// 同义词列表项选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //4对勾5×
                if (e.ColumnIndex == 2)
                {
                    var checkCellRight = (DataGridViewCheckBoxCell)dgvTYC.Rows[e.RowIndex].Cells["Check"];

                    if (checkCellRight.Value != DBNull.Value && Convert.ToBoolean(checkCellRight.Value))
                    {
                        checkCellRight.Value = false;
                    }
                    else
                    {
                        checkCellRight.Value = true;
                    }


                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        string gzcName = dgvTYC.Rows[e.RowIndex].Cells["RuleName"].Value.ToString();
                        string tycName = dgvTYC.Rows[e.RowIndex].Cells["TYName"].Value.ToString();
                        DataTable dt = ssbsbll.GetRuleWord(gzcName, tycName);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            DataRow dr = dt.Rows[0];
                            SYS_SiftBdSyn ssbs = new SYS_SiftBdSyn();
                            ssbs.Ruleword = gzcName;
                            ssbs.BdSyn = tycName;
                            ssbs.SB_CaseCause = dr["BS_CaseCause"].ToString();
                            ssbs.HYCode = dr["HYCode"].ToString();
                            ssbs.Flag = dr["Flag"].ToString();
                            ssbs.WMR = dr["WMA"].ToString();
                            ssbs.WMS = dr["WMB"].ToString();
                            ssbs.ApplicationFlag = dr["BS_ApplicationFlag"].ToString();
                            ssbs.CreatePerson = Gvar.uo.m_displayName;
                            ssbsbll.Add(ssbs);
                        }
                        else
                        {
                            DataTable dt1 = ssbsbll.GetRuleWordNew(gzcName, tycName);
                            if (dt1 != null && dt1.Rows.Count > 0)
                            {
                                DataRow dr = dt1.Rows[0];
                                SYS_SiftBdSyn ssbs = new SYS_SiftBdSyn();
                                ssbs.Ruleword = gzcName;
                                ssbs.BdSyn = tycName;
                                ssbs.SB_CaseCause = dr["BS_CaseCause1"].ToString();
                                ssbs.HYCode = dr["HYCode"].ToString();
                                ssbs.Flag = dr["Flag1"].ToString() == dr["Flag2"].ToString() ? dr["Flag1"].ToString() : "1";
                                ssbs.WMR = dr["WMA"].ToString();
                                ssbs.WMS = dr["WMB"].ToString();
                                ssbs.ApplicationFlag = dr["BS_ApplicationFlag1"].ToString();
                                ssbs.CreatePerson = Gvar.uo.m_displayName;
                                ssbsbll.Add(ssbs);
                            }
                            else
                            {
                                DataTable dt2 = ssbsbll.GetRuleWordByGZC(gzcName);
                                if (dt2 != null && dt2.Rows.Count > 0 && !string.IsNullOrEmpty(clicknode.Tag.ToString()))
                                {
                                    DataRow dr = dt2.Rows[0];
                                    SYS_SiftBdSyn ssbs = new SYS_SiftBdSyn();
                                    ssbs.Ruleword = gzcName;
                                    ssbs.BdSyn = tycName;
                                    ssbs.SB_CaseCause = dr["BS_CaseCause"].ToString();
                                    ssbs.HYCode = dr["HYCode"].ToString();
                                    ssbs.ApplicationFlag = dr["BS_ApplicationFlag"].ToString();
                                    GZCTYCInfo info = new GZCTYCInfo() { GzcName = gzcName, TycName = tycName };
                                    info = GetGzcTycInfo(info);
                                    ssbs.Flag = info.GzcFlag.ToString() == info.TycFlag.ToString() ? info.GzcFlag.ToString() : "1";
                                    ssbs.WMR = info.WMA.ToString();
                                    ssbs.WMS = info.WMB.ToString();

                                    ssbs.CreatePerson = Gvar.uo.m_displayName;
                                    ssbsbll.Add(ssbs);
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(ruleSynforbidword))
                        {
                            GetTYC(ruleSynforbidword);

                        }
                    }
                }
            }
        }
        #endregion

        #region 规则词同义词筛选获取数据
        /// <summary>
        /// 规则词同义词筛选获取数据
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public GZCTYCInfo GetGzcTycInfo(GZCTYCInfo info)
        {
            try
            {
                GZCTYCInfo infoNew = new GZCTYCInfo();
                infoNew.GzcName = info.GzcName;
                infoNew.TycName = info.TycName;
                string ccAYid = caseCausebll.IsParentRealation1(clicknode.Tag.ToString()).CC_ID;
                RequestWord rc = new RequestWord() { content = info.GzcName, caseCauseCode = ccAYid, industryCode = "通用", isSegment = "是" };
                string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
                WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
                if (model.result.code == "1")
                {
                    List<thesaurusModel> thesaurusModels = model.body;
                    Dictionary<string, thesaurusWrodModel> dic = new Dictionary<string, thesaurusWrodModel>();
                    if (thesaurusModels.Count > 0)
                    {
                        foreach (thesaurusModel item in thesaurusModels)
                        {

                            if (item.segmentWord == info.GzcName && item.isStopWord == "否")
                            {
                                //同义词
                                if (item.thesaurusWrods.Count > 0)
                                {

                                    foreach (thesaurusWrodModel item1 in item.thesaurusWrods)
                                    {
                                        if (!dic.ContainsKey(item1.thesaurusWrod))
                                        {
                                            dic.Add(item1.thesaurusWrod, new thesaurusWrodModel() { thesaurusWrod = item1.thesaurusWrod, type = item1.type, wordMeanId = item1.wordMeanId, thesaurusWrodA = item1.thesaurusWrodA, wordBMeanId = item1.wordBMeanId });
                                        }
                                        if (info.TycName == item1.thesaurusWrod)
                                        {
                                            infoNew.TycFlag = item1.type;
                                            infoNew.WMB = Convert.ToInt32(item1.wordMeanId);
                                        }
                                    }
                                    if (dic.Count > 0)
                                    {
                                        twm = null;
                                        GetThesaurusWrodModel(dic, info.GzcName, info.TycName);
                                        if (twm != null && !string.IsNullOrEmpty(twm.thesaurusWrod))
                                        {
                                            infoNew.GzcFlag = twm.type;
                                            infoNew.WMA = Convert.ToInt32(twm.wordMeanId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return infoNew;
                }
                else if (model.result.code == "0")
                {
                    Log.WriteLog("获取词库数据失败！规则词:" + info.GzcName + " content:" + content + model.result.message);
                    return new GZCTYCInfo();
                }
                else
                {
                    return new GZCTYCInfo();
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("调用获取词库分词接口发生错误：规则词:" + info.GzcName + " content:" + content + ex.Message);
                return new GZCTYCInfo();
            }
        }
        #endregion

        #region 递归遍历规则词
        /// <summary>
        /// 递归遍历规则词
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="gzcName"></param>
        /// <param name="tycName"></param>
        /// <returns></returns>
        public void GetThesaurusWrodModel(Dictionary<string, thesaurusWrodModel> dic, string gzcName, string tycName)
        {
            foreach (var item in dic.Keys)
            {
                if (item == tycName)
                {
                    if (dic[item].thesaurusWrodA == gzcName)
                    {
                        twm = dic[item];
                        break;
                    }
                    else
                    {
                        GetThesaurusWrodModel(dic, gzcName, dic[item].thesaurusWrodA);
                    }
                }

            }
        }
        #endregion

        #region 筛选同义词按钮事件
        /// <summary>
        /// 筛选同义词
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSXTYC_Click(object sender, EventArgs e)
        {
            TYCSelect tyc = new TYCSelect(1);
            tyc.ShowDialog();
            if (!string.IsNullOrEmpty(ruleSynforbidword))
            {
                GetTYC(ruleSynforbidword);
            }
        }
        #endregion

        #region 节点重新执行分词
        /// <summary>
        /// 节点重新执行分词
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加要素ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (editnode != null)
            {
                Task.Run(() => { ReplayComputer(editnode.Parent.Text == "属性" ? editnode.Parent.Parent.Tag.ToString() : editnode.Parent.Tag.ToString(), editnode.Tag.ToString(), 1); });

            }
        }
        #endregion

        #region 筛除词库
        /// <summary>
        /// 筛除词库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSCCK_Click(object sender, EventArgs e)
        {
            TYCSelect tyc = new TYCSelect(2);
            tyc.ShowDialog();

            GetGPC();
        }
        #endregion

        #region 高频词列表点击事件
        /// <summary>
        /// 高频词列表点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvCP_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e != null && e.RowIndex > -1)
            {
                //4对勾5×
                if (e.ColumnIndex == 3)
                {
                    var checkCellRight = (DataGridViewCheckBoxCell)dgvCP.Rows[e.RowIndex].Cells["check2"];

                    if (checkCellRight.Value != DBNull.Value && Convert.ToBoolean(checkCellRight.Value))
                    {
                        checkCellRight.Value = false;
                    }
                    else
                    {
                        checkCellRight.Value = true;
                    }
                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        string content = dgvCP.Rows[e.RowIndex].Cells["content"].Value.ToString();
                        if (sswb.GetSiftWordByWord(content) == 0)
                        {
                            SYS_SiftWord ssw = new SYS_SiftWord();
                            ssw.Siftword = content;
                            ssw.CreatePerson = Gvar.uo.m_displayName;
                            sswb.Add(ssw);

                        }
                        dgvCP.Rows.RemoveAt(e.RowIndex);
                        //GetGPC();
                    }
                }
            }
        }
        #endregion

        #region 树展开全部事件
        /// <summary>
        /// 树展开全部事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (editnode != null && !string.IsNullOrEmpty(editnode.Tag.ToString()))
            {
                var findNode = FindNode(editnode.Tag.ToString());
                if (findNode != null) findNode.ExpandAll();
            }
        }
        #endregion

        #region 表述数据键盘上下按键事件
        /// <summary>
        /// 表述数据键盘上下按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvBS_KeyDown(object sender, KeyEventArgs e)
        {
            int row = this.dgvBS.CurrentRow.Index;//获取当前选中的行数
            int roww = dgvBS.Rows.Count - 1;//获取最后一行
            if (e.KeyCode == Keys.Down)//键盘按方向下
            {
                if (row == roww)
                {
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[row].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[row].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[row].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }
                }
                else
                {
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[row + 1].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[row + 1].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[row + 1].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }
                }
            }
            else if (e.KeyCode == Keys.Up)//键盘按方向上
            {
                if (row - 1 < 0)
                {
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[0].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[0].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[0].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }
                }
                else
                {
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[row - 1].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[row - 1].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[row - 1].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }

                }
            }
            if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)//键盘按方向上
            {
                if (row - 1 < 0)
                {
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[0].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[0].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[0].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }
                }
                else
                {
                    rtbNew1.Text = "";
                    rtbNew1.Text = dgvBS.Rows[row - 1].Cells["EW_Content"].Value.ToString();
                    string ruleWord = dgvBS.Rows[row - 1].Cells["Ruleword"].Value.ToString();
                    txbRemark.Text = "";
                    txbRemark.Text = dgvBS.Rows[row - 1].Cells["Remark"].Value.ToString();
                    if (!string.IsNullOrEmpty(ruleWord))
                    {
                        string[] res = ruleWord.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                        if (res.Length > 0)
                        {
                            foreach (var item in res.ToList())
                            {
                                PositionExtractValueNew(item);
                            }
                        }
                    }

                }
            }
        }
        #endregion

        #region 是否取案例数据框点击事件
        /// <summary>
        /// 是否取案例数据框点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkHasOwnNode_CheckedChanged(object sender, EventArgs e)
        {
            if (chkHasOwnNode.Checked)
            {
                txbALNum.Text = "";
                txbALNum.ReadOnly = false;
            }
            else
            {
                txbALNum.Text = "";
                txbALNum.ReadOnly = true;
            }
        }
        #endregion

        #region 节点分词事件
        /// <summary>
        /// 节点分词事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 节点分词ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ElementWords.Clear();
                string ccid = editnode.Tag.ToString();
                sysElementRuleWords = serrbll.GetSysElementWord();
                //获取当前节点的末级案由节点进行该案由下的所有节点进行分词
                string ccAYid = caseCausebll.IsParentRealation1(ccid).CC_ID;
                if (editnode != null && !string.IsNullOrEmpty(ccid) && !string.IsNullOrEmpty(ccAYid))
                {
                    dtCaseCause = caseCausebll.GetCriminalNodesByData(ccid);

                    if (dtCaseCause != null && dtCaseCause.Rows.Count > 0)
                    {
                        dtSysElementSiftWord.Clear();
                        //获取主体词表数据
                        dtSysElementSiftWord = seswbll.GetSysElementSiftWord(ccAYid);
                        foreach (DataRow dr in dtCaseCause.Rows)
                        {
                            string ccId = dr["CC_ID"].ToString();
                            string ccName = dr["CC_Name"].ToString();
                            if (!string.IsNullOrEmpty(ccId))
                            {
                                GetWordNew(ccName, ccId, ccAYid);
                            }
                        }
                    }
                }
                MessageBox.Show("节点分词结束！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("节点分词发生错误：" + ex.Message);
            }
        }
        #endregion

        #region 获取节点分词
        /// <summary>
        /// 获取节点分词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ccid"></param>
        /// <param name="caseCauseCode"></param>
        public void GetWordNew(string content, string ccid, string caseCauseCode)
        {
            try
            {
                RequestWord rc = new RequestWord() { content = content.Trim(), caseCauseCode = caseCauseCode, industryCode = "通用", isSegment = "是" };
                string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
                WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
                if (model.result.code == "1")
                {
                    List<string> segments = new List<string>();
                    StringBuilder sbRule = new StringBuilder();
                    StringBuilder sbStop = new StringBuilder();


                    List<thesaurusModel> thesaurusModels = model.body;
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    if (thesaurusModels.Count > 0)
                    {
                        //分词的组合
                        List<List<string>> thesaursTY = new List<List<string>>();
                        List<List<string>> thesaursJY = new List<List<string>>();
                        StringBuilder sbTy = new StringBuilder();
                        StringBuilder sbJy = new StringBuilder();
                        foreach (thesaurusModel item in thesaurusModels)
                        {
                            sbTy.Clear();
                            sbJy.Clear();
                            //排除主体词
                            if (dtSysElementSiftWord != null && dtSysElementSiftWord.Rows.Count > 0 && dtSysElementSiftWord.Select(" Siftword='" + item.segmentWord.Trim() + "' ").Length > 0)
                            {
                                continue;
                            }
                            //返回的接口中分词会有重复，需求进行去重
                            if (segments.Contains(item.segmentWord))
                            {
                                continue;
                            }
                            else
                            {
                                segments.Add(item.segmentWord);
                            }
                            if (item.isStopWord == "否")
                            {
                                if (!dic.ContainsKey(item.segmentWord))
                                {
                                    dic.Add(item.segmentWord, "");
                                }
                                sbRule.Append(item.segmentWord + "，");
                                //同义词
                                if (item.thesaurusWrods.Count > 0)
                                {
                                    //每一个分词的组合
                                    List<string> l1 = new List<string>();
                                    l1.Add(item.segmentWord);
                                    if (item.thesaurusWrods != null)
                                    {
                                        foreach (thesaurusWrodModel item1 in item.thesaurusWrods)
                                        {
                                            //过滤筛除词
                                            if (dtBdSyn != null && dtBdSyn.Rows.Count > 0)
                                            {
                                                if (dtBdSyn.Select(" Ruleword='" + item.segmentWord + "' and BdSyn='" + item1.thesaurusWrod + "' ").Length > 0)
                                                {
                                                    continue;
                                                }
                                            }
                                            if (!l1.Contains(item1.thesaurusWrod))
                                            {
                                                l1.Add(item1.thesaurusWrod);
                                                sbTy.Append(item1.thesaurusWrod + ",");
                                            }
                                        }
                                    }
                                    thesaursTY.Add(l1);
                                }
                                else
                                {
                                    List<string> l1 = new List<string>();
                                    l1.Add(item.segmentWord);
                                    thesaursTY.Add(l1);
                                }
                                //禁用词
                                if (item.forbiddenWords.Count > 0)
                                {
                                    //每一个分词的组合
                                    List<string> l2 = new List<string>();
                                    foreach (wordModel item1 in item.forbiddenWords)
                                    {
                                        if (item1.word != null)
                                        {
                                            foreach (string item2 in item1.word)
                                            {
                                                if (!l2.Contains(item2))
                                                {
                                                    l2.Add(item2);
                                                    sbJy.Append(item2 + ",");
                                                }
                                            }
                                        }
                                    }
                                    thesaursJY.Add(l2);
                                }
                                string sbTyNew = sbTy.ToString().Length > 0 ? sbTy.ToString().Remove(sbTy.ToString().Length - 1, 1) : "";
                                string sbJyNew = sbJy.ToString().Length > 0 ? sbJy.ToString().Remove(sbJy.ToString().Length - 1, 1) : "";
                                if (dic.ContainsKey(item.segmentWord))
                                {
                                    dic[item.segmentWord] = sbTyNew + ":" + sbJyNew;
                                }
                            }
                            else if (item.isStopWord == "是")
                            {
                                sbStop.Append(item.segmentWord + "，");
                            }

                        }
                        if (!ElementWords.ContainsKey(ccid))
                        {
                            string ruleWord = sbRule.ToString().Length > 0 ? sbRule.ToString().Remove(sbRule.ToString().Length - 1, 1) : "";
                            string stopWord = sbStop.ToString().Length > 0 ? sbStop.ToString().Remove(sbStop.ToString().Length - 1, 1) : "";
                            Dictionary<string, WordTYJY> WordTYJY1 = new Dictionary<string, WordTYJY>();
                            WordTYJY1.Add(content, new WordTYJY() { WordTY = thesaursTY, WordJY = thesaursJY });
                            ElementWords.Add(ccid, new SysElementData()
                            {
                                CCID = ccid,
                                CCName = content,
                                RuleWord = ruleWord,
                                StopWord = stopWord,
                                WordTYJY = WordTYJY1
                            });
                            StringBuilder sbResult = new StringBuilder();
                            if (dic.Count > 0)
                            {
                                foreach (var item in dic.Keys)
                                {
                                    sbResult.Append(item + ":" + dic[item] + "$");
                                }
                            }
                            if (sysElementRuleWords != null && sysElementRuleWords.Rows.Count > 0 && sysElementRuleWords.Select(" CC_ID='" + ccid + "' ").Length > 0)
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord, EW_ID = sysElementRuleWords.Select(" CC_ID='" + ccid + "' ")[0]["EW_ID"].ToString(), Rule_Synforbidword = sbResult.ToString() };
                                serrbll.UpdateName(serr);
                            }
                            else
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord, Rule_Synforbidword = sbResult.ToString() };
                                serrbll.Add(serr);
                            }
                        }
                    }
                    else
                    {
                        if (!ElementWords.ContainsKey(ccid))
                        {
                            string ruleWord = "";
                            string stopWord = "";
                            Dictionary<string, WordTYJY> WordTYJY1 = new Dictionary<string, WordTYJY>();
                            WordTYJY1.Add("", new WordTYJY() { WordTY = new List<List<string>>(), WordJY = new List<List<string>>() });
                            ElementWords.Add(ccid, new SysElementData()
                            {
                                CCID = ccid,
                                CCName = content,
                                RuleWord = ruleWord,
                                StopWord = stopWord,
                                WordTYJY = WordTYJY1
                            });
                            if (sysElementRuleWords != null && sysElementRuleWords.Rows.Count > 0 && sysElementRuleWords.Select(" CC_ID='" + ccid + "' ").Length > 0)
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord, EW_ID = sysElementRuleWords.Select(" CC_ID='" + ccid + "' ")[0]["EW_ID"].ToString(), Rule_Synforbidword = "" };
                                serrbll.UpdateName(serr);
                            }
                            else
                            {
                                SYS_Element_Ruleword_Rel serr = new SYS_Element_Ruleword_Rel() { CC_ID = ccid, Ruleword = ruleWord, Stopword = stopWord, Rule_Synforbidword = "" };
                                serrbll.Add(serr);
                            }
                        }
                    }
                }
                else if (model.result.code == "0")
                {
                    Log.WriteLog("添加失败！ccid:" + ccid + " content:" + content + model.result.message);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("调用获取词库分词接口发生错误：ccid:" + ccid + " content:" + content + ex.Message);
            }
        }
        #endregion

        #region 规则管理界面单击项事件
        /// <summary>
        /// 规则管理界面单击项事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvGZ_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //4对勾5×
                if (e.ColumnIndex == 5)
                {
                    var checkCellRight = (DataGridViewCheckBoxCell)dgvGZ.Rows[e.RowIndex].Cells["lock1"];

                    if (checkCellRight.Value != DBNull.Value && Convert.ToBoolean(checkCellRight.Value))
                    {
                        checkCellRight.Value = false;
                    }
                    else
                    {
                        checkCellRight.Value = true;
                    }

                    string ewID = dgvGZ.Rows[e.RowIndex].Cells["EW_ID1"].Value.ToString();

                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        serrbll.UpdateElementLock(ewID, true);
                    }
                    else
                    {
                        serrbll.UpdateElementLock(ewID, false);
                    }
                    tabControl2_SelectedIndexChanged(null, null);
                }
                else
                {
                    if (e != null && e.RowIndex > -1)
                    {
                        string ccid = dgvGZ.Rows[e.RowIndex].Cells["CC_ID"].Value.ToString();
                        ccName = dgvGZ.Rows[e.RowIndex].Cells["CC_Name"].Value.ToString();
                        ruleSynforbidword = dgvGZ.Rows[e.RowIndex].Cells["Rule_Synforbidword"].Value.ToString();
                        GetTYC(ruleSynforbidword);
                    }
                }
            }
        }
        #endregion

        #region 节点树框按键事件
        /// <summary>
        /// 节点树框按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')//回车
            {
                QueryNode();
            }
        }
        #endregion

        #region 规则管理界面双击事件
        /// <summary>
        /// 规则管理界面双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvGZ_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e != null && e.RowIndex > -1 && e.ColumnIndex == 1)
            {
                int dataGridIndex = e.RowIndex;
                string ccid = dgvGZ.Rows[e.RowIndex].Cells["CC_ID"].Value.ToString();
                string ruleWord = dgvGZ.Rows[e.RowIndex].Cells["Ruleword1"].Value.ToString();
                string xmlPath = dgvGZ.Rows[e.RowIndex].Cells["XmlPath"].Value.ToString();
                string ewID = dgvGZ.Rows[e.RowIndex].Cells["EW_ID1"].Value.ToString();
                string ruleSynWord = dgvGZ.Rows[e.RowIndex].Cells["Rule_Synforbidword"].Value.ToString();
                RuleWordUpdate rwu = new RuleWordUpdate(xmlPath, ruleWord, ewID, ruleSynWord, ccid);
                var dialogResult = rwu.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    tabControl2_SelectedIndexChanged(null, null);
                    //选中行并滚动到指定位置
                    if (dataGridIndex >= 0 && this.dgvGZ.Rows.Count > 0 && this.dgvGZ.Rows.Count + 1 > dataGridIndex)
                    {
                        this.dgvGZ.Rows[dataGridIndex].Selected = true;
                        dgvGZ.CurrentCell = dgvGZ.Rows[dataGridIndex].Cells["Ruleword1"];
                        string RuleWord = dgvGZ.Rows[e.RowIndex].Cells["Rule_Synforbidword"].Value.ToString();
                        if (!string.IsNullOrEmpty(RuleWord))
                        {
                            DataTable dt = new DataTable();
                            dt.Columns.Add(new DataColumn("RuleName"));
                            dt.Columns.Add(new DataColumn("TYName"));
                            dt.Columns.Add(new DataColumn("Check"));
                            DataTable dtJY = new DataTable();
                            dtJY.Columns.Add(new DataColumn("RuleName"));
                            dtJY.Columns.Add(new DataColumn("JYName"));
                            //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                            string[] res = RuleWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                            if (res.Length > 0)
                            {

                                foreach (var item in res)
                                {
                                    List<string> ty = new List<string>();
                                    List<string> jy = new List<string>();
                                    string[] lis = item.Split(':');
                                    if (lis.Length > 0)
                                    {
                                        string gzc = string.Empty;
                                        if (!string.IsNullOrWhiteSpace(lis[0]))
                                        {
                                            gzc = lis[0];
                                        }
                                        if (!string.IsNullOrWhiteSpace(gzc) && !string.IsNullOrWhiteSpace(lis[1]))
                                        {
                                            string[] st = lis[1].Split(',');
                                            if (st.Length > 0)
                                            {
                                                foreach (var item1 in st)
                                                {
                                                    if (!string.IsNullOrEmpty(item1))
                                                    {
                                                        DataRow dr = dt.NewRow();
                                                        dr["RuleName"] = gzc;
                                                        dr["TYName"] = item1;
                                                        dt.Rows.Add(dr);
                                                    }
                                                }
                                            }
                                        }
                                        if (!string.IsNullOrWhiteSpace(gzc) && !string.IsNullOrWhiteSpace(lis[2]))
                                        {
                                            string[] st = lis[2].Split(',');
                                            if (st.Length > 0)
                                            {
                                                foreach (var item1 in st)
                                                {
                                                    if (!string.IsNullOrEmpty(item1))
                                                    {
                                                        DataRow dr = dtJY.NewRow();
                                                        dr["RuleName"] = gzc;
                                                        dr["JYName"] = item1;
                                                        dtJY.Rows.Add(dr);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                dgvTYC.DataSource = dt;
                            }
                            else
                            {
                                DataTable dtt = (DataTable)dgvTYC.DataSource;
                                if (dtt != null)
                                { dtt.Rows.Clear(); }
                                dgvTYC.DataSource = dtt;
                            }

                            if (dtJY != null && dtJY.Rows.Count > 0)
                            {
                                dgvJYC.DataSource = dt;
                            }
                            else
                            {
                                DataTable dtt = (DataTable)dgvJYC.DataSource;
                                if (dtt != null)
                                { dtt.Rows.Clear(); }
                                dgvJYC.DataSource = dtt;
                            }
                        }
                        else
                        {
                            DataTable dtt = (DataTable)dgvTYC.DataSource;
                            if (dtt != null)
                            { dtt.Rows.Clear(); }
                            dgvTYC.DataSource = dtt;
                            DataTable dtt1 = (DataTable)dgvJYC.DataSource;
                            if (dtt1 != null)
                            { dtt1.Rows.Clear(); }
                            dgvJYC.DataSource = dtt1;
                        }
                    }
                }
            }
        }
        #endregion

        #region 表述列表数据加载
        /// <summary>
        ///表述列表数据加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            if (clicknode != null)
            {
                StringBuilder sb = new StringBuilder();
                //逻辑段 (全部 本院认为 审理查明)
                if (!string.IsNullOrEmpty(cmbLJD.Text.Trim()))
                {
                    switch (cmbLJD.Text.Trim())
                    {
                        case "全部":
                            sb.Append(" ");
                            break;
                        case "本院认为":
                            sb.Append(" and ParagraphTypeId=0 ");
                            break;
                        case "审理查明":
                            sb.Append(" and ParagraphTypeId=1 ");
                            break;
                    }
                }
                //是否包含法条内容 （全部  包含法条内容   不包含法条内容）
                if (!string.IsNullOrEmpty(cmbFT.Text.Trim()))
                {
                    switch (cmbFT.Text.Trim())
                    {
                        case "全部":
                            sb.Append(" ");
                            break;
                        case "包含法条内容":
                            sb.Append(" and IsContainsFT=1 ");
                            break;
                        case "不包含法条内容":
                            sb.Append(" and IsContainsFT=0 ");
                            break;
                    }
                }
                //数据标记(全部 空 新增节点数据 下级节点数据)
                if (cmbDataBJ.Text == "全部")
                {

                }
                else if (cmbDataBJ.Text == "")
                {
                    sb.Append(" and( DataSign='' or DataSign is null ) ");
                }
                else if (!string.IsNullOrEmpty(cmbDataBJ.Text.Trim()))
                {
                    DataRow[] dr = dtCaseMark.Select(" AM_Name='" + cmbDataBJ.Text.Trim() + "' ");
                    if (dr.Length > 0)
                    {
                        sb.Append(" and DataSign='" + dr[0]["AM_ID"].ToString() + "' ");
                    }
                }
                //表述句内容模糊匹配
                if (!string.IsNullOrEmpty(txbSearch.Text.Trim()))
                {
                    sb.Append(" and EW_Content like '%" + txbSearch.Text.Trim() + "%' ");
                }

                int Num = ewbll.GetProcessCaseCount(clicknode.Tag.ToString(), sb.ToString());
                var startRowIndex = e.StartRowIndex;
                //var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                Log.WriteLog("民事数据处理（智能数据部用）获取表述数据开始时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                DateTime timeBegin = DateTime.Now;
                DataTable dt1 = ewbll.GetExtraceContentNew(clicknode.Tag.ToString(), 100, e.CurrentPageNumber, sb.ToString());
                TimeSpan ts = DateTime.Now - timeBegin;
                Log.WriteLog("获取表述数据结束" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + ts.TotalSeconds + "秒");
                timeGetData = DateTime.Now;

                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    dt1 = PublicMethod.AddDataTableNum(dt1);
                    ////高频词统计公式：当前分词所在的表述句数量/当前节点的所有表述句数量
                    //Dictionary<string, string> dics = new Dictionary<string, string>();
                    //int zum = dt1.Rows.Count;
                    //foreach (DataRow dr in dt1.Rows)
                    //{
                    //    if (!string.IsNullOrEmpty(dr["Word"].ToString()))
                    //    {
                    //        string[] strs = dr["Word"].ToString().Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                    //        if (strs.Length > 0)
                    //        {
                    //            foreach (var item in strs.ToList())
                    //            {
                    //                if (dtSiftWord.Select("Siftword='" + item + "' ").Length > 0)
                    //                {
                    //                    continue;
                    //                }
                    //                if (!dics.ContainsKey(item))
                    //                {
                    //                    dics.Add(item, "1");
                    //                }
                    //                else
                    //                {
                    //                    dics[item] = Convert.ToString(Convert.ToInt32(dics[item]) + 1);
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    //if (dics.Count > 0)
                    //{
                    //    foreach (var item in dics.Keys.ToArray())
                    //    {
                    //        if ((double)Convert.ToInt32(dics[item]) / zum > 0.5)
                    //        {
                    //            dics[item] = ((double)Convert.ToInt32(dics[item]) / zum).ToString("P");
                    //        }
                    //        else
                    //        {
                    //            dics.Remove(item);
                    //        }
                    //    }
                    //}
                    //if (dics.Count > 0)
                    //{
                    //    DataTable dt = new DataTable();
                    //    dt.Columns.Add("content");
                    //    dt.Columns.Add("CP");
                    //    foreach (var item in dics.Keys)
                    //    {
                    //        DataRow dr = dt.NewRow();
                    //        dr["content"] = item;
                    //        dr["CP"] = dics[item];
                    //        dt.Rows.Add(dr);
                    //    }
                    //    if (dt != null && dt.Rows.Count > 0)
                    //    {
                    //        dt = PublicMethod.AddDataTableNum(dt);
                    //        dgvCP.DataSource = dt;
                    //    }
                    //}
                    //else
                    //{
                    //    DataTable dtt = (DataTable)dgvCP.DataSource;
                    //    if (dtt != null)
                    //    { dtt.Rows.Clear(); }
                    //    dgvCP.DataSource = dtt;

                    //}
                    //ts = DateTime.Now - timeGetData;
                    //Log.WriteLog("进行高频词数据统计" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " 耗时：" + ts.TotalSeconds + "秒");
                    if (dt1.Rows.Count > 0)
                    {
                        e.TotalCount = Num;
                        //var newdt = new DataTable();
                        //newdt = dt1.Clone();
                        //var dr = dt1.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                        //for (var i = 0; i < dr.Length; i++)
                        //{
                        //    newdt.ImportRow(dr[i]);
                        //}
                        dgvBS.DataSource = dt1;
                    }
                }
                else
                {
                    DataTable dtt = (DataTable)dgvBS.DataSource;
                    if (dtt != null)
                    { dtt.Rows.Clear(); }
                    dgvBS.DataSource = dtt;
                    DataTable dtt1 = (DataTable)dgvCP.DataSource;
                    if (dtt1 != null)
                    { dtt1.Rows.Clear(); }
                    dgvCP.DataSource = dtt1;
                }
            }
        }
        #endregion

        #region 根据条件进行查询表述管理
        /// <summary>
        /// 根据条件进行查询表述管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }
        #endregion

        /// <summary>
        /// 保存数据标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveDataSign_Click(object sender, EventArgs e)
        {
            string dataSign = cmbDataSignSet.SelectedValue.ToString().Trim();
            int num = 0;
            for (var i = 0; i <= dgvBS.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dgvBS.Rows[i].Cells["CheckBS"];
                if (Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要保存的数据后再试");
                return;
            }
            try
            {
                StringBuilder sb = new StringBuilder();
                for (var i = 0; i <= dgvBS.Rows.Count - 1; i++)
                {
                    var check = (DataGridViewCheckBoxCell)dgvBS.Rows[i].Cells["CheckBS"];
                    if (Convert.ToBoolean(check.Value))
                    {
                        string ewID = dgvBS.Rows[i].Cells["EW_ID"].Value.ToString();
                        sb.Append("'" + ewID + "',");
                    }
                }
                bool res = ewbll.UpdateProcessCaseDataSign(sb.ToString().Substring(0, sb.Length - 1), dataSign);
                if (res)
                {
                    MessageBox.Show("保存成功！");
                    dataPagerMain.ChangePageNumber(1);
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存数据标记出错：" + ex.Message);
                return;
            }
        }

    }
    #region 规则词同义词信息
    /// <summary>
    /// 规则词同义词信息
    /// </summary>
    public class GZCTYCInfo
    {
        /// <summary>
        /// 规则词名称
        /// </summary>
        public string GzcName { get; set; }

        /// <summary>
        /// 同义词名称
        /// </summary>
        public string TycName { get; set; }

        /// <summary>
        /// 规则词Flag
        /// </summary>
        public int GzcFlag { get; set; }

        /// <summary>
        /// 同义词Flag
        /// </summary>
        public int TycFlag { get; set; }

        /// <summary>
        /// 规则词词义
        /// </summary>
        public int WMA { get; set; }

        /// <summary>
        /// 同义词词义
        /// </summary>
        public int WMB { get; set; }

    }
    #endregion
}